Reputation: 332
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:
Constraints:
Upvotes: 1
Views: 2835
Reputation: 2786
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
Upvotes: 3
Reputation: 1486
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;
Upvotes: 1
Reputation: 99
Use this custom TextView class "HPGrowingTextView", it's work for me.
Below is Link:-
https://github.com/HansPinckaers/GrowingTextView
Upvotes: 0
Reputation: 478
Instead of UITextview make a custom UILable class and set Constraint like I show in follwing image.
Upvotes: 1
Reputation: 53
you can delete trailing space to superview to get width from text lenght can you try?
Upvotes: 0