I'm currently in the process of building a social networking app that displays the user's posts in a table. Each post will be displayed in one cell of the table. Because I don't know how much the user will type for one post, I need to set the text view size according to the amount of text typed by the user. The problem is that my current implementation is not working and behaving strangely.
Here is my table code:
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let cell : UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("HomeCell") as? UITableViewCell
let post : Post = tblData[indexPath.row]
//Get all custom cell components
let userLbl = cell?.viewWithTag(101) as UILabel
let timeLbl = cell?.viewWithTag(102) as UILabel
let postLbl = cell?.viewWithTag(103) as UITextView
let profilePic = cell?.viewWithTag(100) as UIImageView
let postPic = cell?.viewWithTag(104) as UIImageView
//Post lbl properties
let textHeight = textViewDidChange(postLbl)
postLbl.frame.size.height = CGFloat(textHeight)
//postLbl.selectable = false
//Individual height variables
let postInfoHeight = 66 as CGFloat
var postHeight = 8 + CGFloat(textHeight)
var imgHeight = 8 + postPic.frame.height as CGFloat
if post.postInformation == "" {
postLbl.removeFromSuperview()
postHeight = 0
}
if post.img == nil {
postPic.removeFromSuperview()
imgHeight = 0
}
//Change the autolayout constraints so it works properly
return postInfoHeight + postHeight + imgHeight
}
and here is the code that calculates the height of the text view:
func textViewDidChange(textView : UITextView) -> Float {
let content : NSString = textView.text
let oneLineSize = content.sizeWithAttributes(["NSFontSizeAttribute": UIFont.systemFontOfSize(14.0)])
let contentSize = CGSizeMake(textView.frame.width, oneLineSize.height * round(oneLineSize.width/textView.frame.width))
return Float(contentSize.height)
}
I can't understand why this isn't giving me the correct results. If anyone can spot an error or suggest how to solve this issue I'd really appreciate it. Thanks in advance!