开发者

How to set height of UITextView according to its content in objective c

I have开发者_如何学C a UITextView and want to set its height as per its content changes.

How can I get height of the content.

Please guide me.

Thanks in advance.


If you want to calculate height of your UITextView for some text then you can use such method:

CGSize textViewSize = [text sizeWithFont:[UIFont fontWithName:@"Marker Felt" size:20] 
                       constrainedToSize:CGSizeMake(WIDHT_OF_VIEW, FLT_MAX) 
                       lineBreakMode:UILineBreakModeTailTruncation];

In fontWithName define font that you are using in UITextView, in size parameter - size of your text in UITextView. Replace WIDHT_OF_VIEW width width of your UITextView.

textViewSize.height will contain height that UITextField to display text without scrolling


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    CGRect frame = _textView.frame;
    frame.size.height = _textView.contentSize.height;
    _textView.frame = frame;
}


You can calculate the size of the text with the method from UIStringDrawing category:

CGSize textSize = [textView.text sizeWithFont:font 
                                 forWidth:textWidth 
                                 lineBreakMode: UILineBreakModeWordWrap];


CGSize countentSize = textView.contentSize;
int numberOfLinesNeeded = countentSize.height / textView.font.lineHeight;
int numberOfLinesInTextView = textView.frame.size.height / textView.font.lineHeight;
CGRect textViewFrame= textView.frame;
textViewFrame.size.height = numberOfLinesNeeded * textView.font.lineHeight;
[textView setFrame:textViewFrame];


sizeWithFont is deprecated .

CGRect rect = [textView.text boundingRectWithSize:CGSizeMake(textView.frame.size.width, CGFLOAT_MAX)
                                                                    options:NSStringDrawingUsesLineFragmentOrigin
                                                                    attributes:@{NSFontAttributeName: textView.font}
                                                                    context:nil];
        rect.size.width = ceil(rect.size.width);
        rect.size.height = ceil(rect.size.height);

I hope it will help someone. Happy coding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜