Resizing UITextView

前端 未结 10 1448
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 15:52

I have a UITextView added on my UIView. The textview added is not editable, it is just to display some data. The data displayed in the textview is

10条回答
  •  我在风中等你
    2020-12-04 16:21

    There is an answer posted at How do I size a UITextView to its content?

    CGRect frame = _textView.frame;
    frame.size.height = _textView.contentSize.height;
    _textView.frame = frame;
    

    or better(taking into account contentInset thanks to kpower's comment)

    CGRect frame = _textView.frame;
    UIEdgeInsets inset = textView.contentInset;
    frame.size.height = _textView.contentSize.height + inset.top + inset.bottom;
    _textView.frame = frame;
    

    note: If you are going to reference a property of an object many times(e.g. frame or contentInset) it's better to assign it to a local variable so you don't trigger extra method calls(_textView.frame/[_textView frame] are method calls). If you are calling this code a lot(100000s of times) then this will be noticeably slower(a dozen or so method calls is insignificant).

    However... if you want to do this in one line without extra variables it would be

    _textView.frame = CGRectMake(_textView.frame.origin.x, _textView.frame.origin.y, _textView.frame.size.width, _textView.contentSize.height + _textView.contentInset.top + _textView.contentInset.bottom);
    

    at the expense of 5 extra method calls.

提交回复
热议问题