Friday, 4 March 2016

Get the height of the text in textview/textfield

Some times we may have need to set the height of the textfield or textview based on the text size contained in the textfield or textview. 

Before iOS 7, we used sizeWithFont: method  to get the desired height, but now it is deprecated. So to get/set the height of the textview/textfield based on the text to be stored in it, we use:

For example: We have textView to show some text . The text length may be different. What if we have some other view there just touching  the  lower left corner of the text field. Though textView can contain different text say one line or multiple lines of text.  Then the position of that other view depends on the height of the textView.

//get the rect size of the counting text

  //set the attribute of the text, like font size and family and some other option
 NSDictionary *attributes  =@{NSFontAttributeName:[UIFont fontWithName:@"Helvetica Neue" size:14]};



CGRect rect = [[text to be stored in view] boundingRectWithSize:CGSizeMake(txtFieldWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];

Now from rect, we can extract the height and make the changes in the frame of the textfield so that textfield has the proper height to contain the text.
So we have approach like this:

 First calculate the text height to be stored in textView using above mentioned method. Then change the frame of the textView to adjust the text in it. After that also make some changes in the frame of the other view so that it places just touching the lower left corer of the textView.





No comments:

Post a Comment