Reputation: 3868
I have a static table with four sections in it. The third section contains a UITextView that I'd like to resize if the user inputs more than one line. I managed to get this working but my resized textView overdraws the last table section.
I found a lot of older articles on this with different solutions but none really worked for me for my case of static tables.
What I've done was made my controller implement UITextViewDelegate and wrote this method:
func textViewDidChange(textView: UITextView) {
var frame = textView.frame
frame.size.height = textView.contentSize.height
textView.frame = frame
tableView?.beginUpdates()
tableView?.endUpdates()
}
Some articles suggest writing a height constraint and then putting this inside the above method:
let size = reminderNameTextInput.bounds.size
let newSize = reminderNameTextInput.sizeThatFits(CGSize(width: size.width, height: CGFloat.max))
// Resize the cell only when cell's size is changed
if size.height != newSize.height {
UIView.setAnimationsEnabled(false)
tableView?.beginUpdates()
tableView?.endUpdates()
}
Regardless, the outcome is the same: the textView grows and overdraws the next tableviewsection.
How can I solve this?
UPDATE 1: Let me show you what I mean by the text "overgrowing" the parts below it:
UPDATE 2 This is what happens if I recalculate the cell height in heightForRowAtIndexPath. It completely overdraws the sections below it instead of shifting them down:
Upvotes: 0
Views: 256
Reputation: 2032
The following code works for me in the same use case as yours, put it in textViewDidChange:
let size = textView.bounds.size
let newSize = textView.sizeThatFits(CGSize(width: size.width, height: CGFloat.max))
var estimatedHeight = newSize.height > MINIMUM_HEIGHT ? newSize.height : MINIMUM_HEIGHT
textView.frame = CGRectMake(0, 0, textView.frame.width, estimatedHeight)
UIView.setAnimationsEnabled(false)
tableView?.beginUpdates()
tableView?.endUpdates()
UIView.setAnimationsEnabled(true)
Upvotes: 1
Reputation: 1461
Are you using autolayouts? When using autolayouts and size-classes , you can fix the problem from storyboard
UITextView Constraint Setting :
Also you must add the following line in textViewDidChange(textView: UITextView)
method,
tableView?.beginUpdates()
tableView?.endUpdates()
Then should work !
Upvotes: 0