Ratikanta Patra
Ratikanta Patra

Reputation: 1177

Unable to control the width of UITextView

I am making an application where I need to create a UITextView on the screen. The height and width of the TextView should go on increasing as the user types i.e. the height and width of the TextView should change according to its content.

However I have been able to control the height of the TextView through the myTextView.ContentSize.height. But I could not find a way to control the width of the TextView according to its content.

Even myTextView.contentSize.width doesn't work for me.

I am doing all my frame calculations within textViewDidchange delegate method of UITextView.

Any suggestions??

Upvotes: 1

Views: 401

Answers (1)

Mathew Varghese
Mathew Varghese

Reputation: 4527

In the textViewDidChange,

CGSize constraintSize; 
CGSize labelSize; 

constraintSize = CGSizeMake(myTextView.frame.size.width, 480); 

NSString    *text   =   myTextView.text;
text                =   [text stringByTrimmingCharactersInSet: [NSCharacterSet newlineCharacterSet]];
text                =   [text stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];

if([text stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding])
{
    text            =   [text stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
}

// Note that in the below line you must use the font as exact as you use for textview

labelSize           =   [text sizeWithFont:[UIFont systemFontOfSize: 16] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

In the labelSize you can find the expected size of the text view. You can set the frame of myTextView as

myTextView.frame    =   CGRectMake(myTextView.frame.origin.x,myTextView.frame.origin.y,labelSize.width,labelSize.height);

Think this will works for you. Try it. Hope this helps.

Upvotes: 1

Related Questions