1

Need some help. I'm building a chat app and want the chat textView to adjust with the width of the text so if the message is short the textView adjusts accordingly. I'm using autolayout but can't seem to figure out how to dynamically adjust the constraint's constant based on the textView's text line length. Thanks.

How I have it now:

enter image description here

Constraints:

enter image description here

2
  • are you useing UITableViewAutomaticDimension Commented Nov 8, 2016 at 5:19
  • Yeah but that only appears to take care of the height of the cell Commented Nov 8, 2016 at 5:41

5 Answers 5

3

enter image description here

plz remember this steps

1 fix the label width set it's relation to greater than or equal >0

2 take the trailing constraint set it's relation to greater than or equal >0

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you balkaran. Using a label with the trailing constraint set to >= 0 ended up doing the trick
1

Instead of UITextview make a custom UILable class and set Constraint like I show in follwing image.

enter image description here

1 Comment

Thanks chetu. You lead me down the right path. Using a label appears to be the right choice.
1

Programmatically you can do like,

Objective C

- (void)textViewDidChange:(UITextView *)textView {
    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;
}

Swift

let fixedWidth = textView.frame.size.width
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
var newFrame = textView.frame
newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
textView.frame = newFrame;

3 Comments

This doesn't appear the be working. Maybe my constraint is overriding it?
Remove the contraint then try this.
Thanks for the help Aisha. I removed it and it just made it expand beyond its view. But I switched it to a label and with the help of some of the other answers got it to work.
0

you can delete trailing space to superview to get width from text lenght can you try?

1 Comment

if I remove the trailing space to superview the textview expands beyond the view when the text is long.
0

Use this custom TextView class "HPGrowingTextView", it's work for me.

Below is Link:-

https://github.com/HansPinckaers/GrowingTextView

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.