TextView在上下左右分别有一个8px的padding,当使用[NSString sizeWithFont:constrainedToSize:lineBreakMode:]时,需要将UITextView.contentSize.width减去16像素(左右的padding 2 x 8px)。同时返回的高度中再加上16像素(上下的padding),这样得到的才是UITextView真正适应内容的高度。
示例代码如下:
1 | + (float) heightForTextView: (UITextView *)textView WithText: (NSString*) strText{ |
2 | floatfPadding = 16.0;// 8.0px x 2 |
3 | CGSize constraint = CGSizeMake(textView.contentSize.width - fPadding, CGFLOAT_MAX); |
4 |
5 | CGSize size = [strText sizeWithFont: textView.font constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap]; |
6 |
7 | floatfHeight = size.height + 16.0; |
8 |
9 | returnfHeight; |
10 | } |
|
CustomCell 自适应高度 UILabel 自动换行 CGSizetitleBrandSizeForHeight = [titleBrand.textsizeWithFont:titleBrand.font]; CGSizetitleBrandSizeForLines = [titleBrand.textsizeWithFont:titleBrand.fontconstrainedToSize:CGSizeMake(infoWidth,MAXFLOAT)lineBreakMode:UILineBreakModeWordWrap]; titleBrand.numberOfLines=ceil(titleBrandSizeForLines.height/titleBrandSizeForHeight.height); if(titleBrand.numberOfLines<=1) { titleBrand.frame=CGRectMake(5,titleBrand.frame.size.height, infoWidth, titleBrandSizeForHeight.height); }else{ titleBrand.frame=CGRectMake(5,titleBrand.frame.size.height, infoWidth,titleBrand.numberOfLines*titleBrandSizeForHeight.height); } UITextView根据内容自动调整高度- (void)textViewDidChange:(UITextView*)textView{ if(textView.text.length> 20)//一行最多多少字节 { <wbr><wbr><wbr><wbr><wbr>//TextView底面背景图片根据内容自动调整高度</wbr></wbr></wbr></wbr></wbr> UIImage*img = [UIImageimageWithContentsOfFile:[[NSBundlemainBundle]pathForResource:@"inputbox"ofType:@"png"]]; [BgImagesetImage:[imgstretchableImageWithLeft<wbr>CapWidth<span style="color:rgb(0,0,0)">:</span><span style="color:rgb(62,1,216)">21</span>topCapHeight<span style="color:rgb(0,0,0)">:</span><span style="color:rgb(62,1,216)">14</span><span style="color:rgb(0,0,0)">]];</span></wbr> UIFont*font = [UIFontsystemFontOfSize:12]; CGSizesize = [textView.textsizeWithFont:fontconstrainedToSize:CGSizeMake(320,140)lineBreakMode:UILineBreakModeWordWrap]; BgImage.frame=CGRectMake(0,202-size.height+15,320, size.height+28); InputTextVeiw.contentInset=UIEdgeInsetsZero;//以换行为基准 [textViewsetFrame:CGRectMake(51,210-size.height+18,200, size.height+5)]; } } |
本文介绍了如何实现iOS应用中UILabel和UITextView的自适应高度,包括UILabel的文字自动换行及UITextView的内容高度自动调整方法,并提供了具体的实现代码。
3675

被折叠的 条评论
为什么被折叠?



