`

自动调整UITextView/UILabel的高度height

    博客分类:
  • ios
 
阅读更多

(转自) http://tangchuanyao.com/20120507760/ | 一路向前

很多时候都需要依据用户输入的内容自动调整UILabel/UITextView的高度和宽度,特别是UINavigationController的标题,超过一行的时候默认就是「…」我们希望他能换行表示,这样就需要根据内容调整titleView的高度啦。直接贴sample代码,高度和宽度可以根据自己的需要调整。

UILabel Sample code

1
2
3
4
5
6
7
CGRect frame = CGRectMake(20, 0, 280,44);
CGSize labelsize = [titleLabel.text sizeWithFont:[UIFont boldSystemFontOfSize: 16.0f]
                   constrainedToSize:CGSizeMake(320, 44)
                       lineBreakMode:UILineBreakModeTailTruncation];
frame.size.width = labelsize.width;
frame.size.height = labelsize.height;
titleLabel.frame = frame;

UITextView Sample code

1
2
3
4
5
6
CGRect frame = noteTextView.frame;
CGSize size = [noteTextView.text sizeWithFont:noteTextView.font
                        constrainedToSize:CGSizeMake(280, 1000)
                            lineBreakMode:UILineBreakModeTailTruncation];
frame.size.height = size.height > 1 ? size.height + 20 : 64;
noteTextView.frame = frame;

UITextView是UIScrollView的子类,因此有contentSize属性,也可以按如下实现

1
2
3
CGRect frame = noteTextView.frame;
frame.size.height = noteTextView.contentSize.height;
noteTextView.frame = frame;
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics