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 |
float fPadding = 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 |
float fHeight = size.height + 16.0; |
8 |
9 |
return fHeight; |
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)]; } } |