Daniel
Daniel

Reputation: 3868

Resizing UITextView and the section containing it without overdrawing next tableview section

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:

enter image description here

enter image description here

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:

enter image description here

Upvotes: 0

Views: 256

Answers (2)

FruitAddict
FruitAddict

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

Rabindra Nath Nandi
Rabindra Nath Nandi

Reputation: 1461

Are you using autolayouts? When using autolayouts and size-classes , you can fix the problem from storyboard

UITextView Constraint Setting :

  1. Set left, right, top, bottom margin constraint
  2. Change the priority of Content Compression Resistance Prority from 750 to 900 or higher than 750 and Content Hugging Priority 250 t0 260.
  3. Turn off scrolling enabled. enter image description here

    Also you must add the following line in textViewDidChange(textView: UITextView) method,

    tableView?.beginUpdates() tableView?.endUpdates()

Then should work !

Upvotes: 0

Related Questions