Reputation: 11098
Currently I can successfully resize my UITextView according to the amount of text within it.
My problem is that this UITextView is within a UITableViewCell. What I've tried to do is use the height of the resized UITextView to resize the cell by accessing it's frame and setting the height of that.
This is my code:
//dynamically resize textview and cell based on content
self.aboutMeTextView.text = profile["aboutMe"] as String
self.aboutMeTextView.sizeToFit()
self.aboutMeTextView.layoutIfNeeded()
var frame = self.aboutMeTextView.frame as CGRect
frame.size.height = self.aboutMeTextView.contentSize.height
self.aboutMeTextView.frame = frame
var cellFrame = self.aboutMeCell.frame as CGRect
cellFrame.size.height = self.aboutMeTextView.contentSize.height * 2
self.aboutMeCell.frame = cellFrame
It just doesn't work properly. The textView resizes but the cell doesn't resize properly and also my scrollView won't even scroll down enough for me to see the whole of the resized textview. I'm guessing if I can successfully set the cells height, the scrollView height will automatically adjust.
I've looked at similar questions but they haven't helped me.
Would appreciate some help.
Thanks for your time
Upvotes: 0
Views: 2566
Reputation: 966
You can call UITableView.beginUpdates() and UITableView.endUpdates() like so:
extension TableViewCell: UITextViewDelegate {
var delegate: TableViewController!
var row: Int!
func textViewDidChange(_ textView: UITextView) {
delegate.tableView.beginUpdates()
delegate.tableView.endUpdates()
}
}
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.delegate = self
cell.row = indexPath.row
return cell
}
}
Be sure your constraints are set up for your text view in the table view cell.
Upvotes: 1
Reputation: 22343
You can use the UITableView
-method heightForRowAtIndexPath
It returns the height for a row. So you can use the label from the current cell and set the height of the cell to the height of the label:
override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
var cellID = "Cell"
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellID) as UITableViewCell
var yourLabelHeight = cell.yourLabel.size.height
return yourLabelHeight
}
Upvotes: 0