Search code examples
iosuitextviewsizetofit

UITextView, sizeToFit doesnt work


I have a uitextview, I would like to dynamically load it based on the contents, the answer from this link doesnt work on iOS11. https://stackoverflow.com/a/20999067/365384

  CGFloat fixedWidth = textView.frame.size.width;
  CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
  CGRect newFrame = textView.frame;
  newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
   textView.frame = newFrame;

The only way I can do is use constraint update constraint

CGFloat fixedWidth = self.textView .frame.size.width;
CGSize newSize = [self.textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    self.textViewHeightConstraint.constant = newSize.height;

I am working on a universal app, and I dont want use too many constraints in the code. Is there any way to fix it without adding extra constraint?


Solution

  • I have tried layoutifneeds, setneedforlayout, all these functions does not resize the uitextview's containerview, even you change the containerview's size, the uitextview will remain original size.

    After look into the UI hierarchy of uitextview, I figure out a easy way to resize uitextview height is layoutsubviews.

    [self.textview sizeToFit];
    [self.textview layoutSubviews];
    

    You may need to set textview height >= min height in xib file.

    there are a lot questions regarding dynamic height of uitextview, and I cant find this answer, unfortunate I cant post reply to these questions, if you think this answer is helpful, please share it with other similar questions.