dcotter
dcotter

Reputation: 332

UITextView Dynamic Width With Text iOS

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

Upvotes: 1

Views: 2835

Answers (5)

balkaran singh
balkaran singh

Reputation: 2786

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

Upvotes: 3

User511
User511

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

Jain_Taresh
Jain_Taresh

Reputation: 99

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

Below is Link:-

https://github.com/HansPinckaers/GrowingTextView

Upvotes: 0

Chetansinh N Zala
Chetansinh N Zala

Reputation: 478

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

enter image description here

Upvotes: 1

Adrian Salim
Adrian Salim

Reputation: 53

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

Upvotes: 0

Related Questions