Resizing UITextView

前端 未结 10 1449
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 16:40

    You can use setFrame: or sizeToFit.

    UPDATE:

    I use sizeToFit with UILabel, and it works just fine, but UITextView is a subclass of UIScrollView, so I can understand why sizeToFit doesn't produce the desired result.

    You can still calculate the text height and use setFrame, but you might want to take advantage of UITextView's scrollbars if the text is too long.

    Here's how you get the text height:

    #define MAX_HEIGHT 2000
    
    NSString *foo = @"Lorem ipsum dolor sit amet.";
    CGSize size = [foo sizeWithFont:[UIFont systemFontOfSize:14]
                  constrainedToSize:CGSizeMake(100, MAX_HEIGHT)
                      lineBreakMode:UILineBreakModeWordWrap];
    

    and then you can use this with your UITextView:

    [textView setFont:[UIFont systemFontOfSize:14]];
    [textView setFrame:CGRectMake(5, 30, 100, size.height + 10)];
    

    or you can do the height calculation first and avoid the setFrame line:

    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(5, 30, 100, size.height + 10)];
    

提交回复
热议问题