UILabel, UITextView 高度自适应

来源:互联网 发布:ssr linux 客户端配置 编辑:程序博客网 时间:2024/05/17 05:51

1. LineBreakMode

NSString *strText = @"String For Text";

UIFont = [UIFont systemFontOfSize:15.0f];

CGSize *size = [strText sizeWithFont:font constrainedToSize:CGSizeMake(lbTest.frame.size.width, NSIntegerMax) lineBreakMode:UILineBreakModeWordWrap];

CGRect rect = lbTest.frame;

rect.size.height = size.height;

[lbTest setFrame:rect];


2. sizeToFit

这种方式适用与UILabel,能自适应宽度,不会自动换行,如果需要自适应高度,需要给出换行符

UILabel *label;

[label sizeToFit];


3. contentSize

这种方式适合UITextView,因为UITextView继承与UIScrollView,所以用txtView_.contentSize可取到其内部滚动区域大小,即通常情况下的实际内容大小

CGFloat height = txtView_.contentSize.height;

CGRect rect = txtView_.frame;

rect.size.height = height;

[txtView_ setFrame:rect];


注:如果设定过UITextView的AutoSize有时取到的height值会有所不同,例如 如果设定高度AutoSize,则取到的height为实际高度的两倍

0 0