How can I make the TableViewCell change height to make the UILabel fit?
I am not using auto layout in my project, and because this is a big project I am not going to change to that either - so I need a fix that works without auto layout.
This is my CommentsViewController.swift
code:
import UIKit
import Parse
import ActiveLabel
class CommentsViewController: UITableViewController, UITextFieldDelegate {
var commentsArray: [String] = []
var currentObjID = ""
@IBOutlet var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
self.textField.delegate = self
queryComments()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func queryComments(){
self.commentsArray.removeAll()
let query = PFQuery(className:"currentUploads")
query.whereKey("objectId", equalTo: self.currentObjID)
query.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error: NSError?) -> Void in
if error == nil {
if let objects = objects {
for object in objects {
let list: AnyObject? = object.objectForKey("comments")
self.commentsArray = list! as! NSArray as! [String]
self.tableView.reloadData()
self.textField.text = ""
}
}
} else {
print("\(error?.userInfo)")
}
}
self.sendButton.enabled = true
self.refreshButton.enabled = true
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return commentsArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:TableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell;
if self.commentsArray.count > indexPath.row{
cell.commentsText.font = UIFont.systemFontOfSize(15.0)
cell.commentsText.text = commentsArray[commentsArray.count - 1 - indexPath.row]
cell.commentsText.numberOfLines = 0
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
let height:CGFloat = self.calculateHeightForString(commentsArray[indexPath.row])
return height + 70.0
}
func calculateHeightForString(inString:String) -> CGFloat
{
let messageString = inString
let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(15.0)]
let attrString:NSAttributedString? = NSAttributedString(string: messageString, attributes: attributes)
let rect:CGRect = attrString!.boundingRectWithSize(CGSizeMake(300.0,CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context:nil )//hear u will get nearer height not the exact value
let requredSize:CGRect = rect
return requredSize.height //to include button's in your tableview
}
}
This makes all the cells very big, even the cells that only has 1 line. Any ideas?