1 -(void)labelHeight 2 3 { 4 UILabel *label = [[UILabel alloc]init]; 5 label.numberOfLines = 0; // 需要把显示行数设置成无限制 6 label.font = [UIFont systemFontOfSize:15]; 7 label.textAlignment = NSTextAlignmentCenter; 8 label.text = @"*****************************"; 9 CGSize size = [self sizeWithString:label.text font:label.font]; 10 label.bounds = CGRectMake(0, 0, size.width, size.height); 11 }
//封装成方法提高复用性
1 -(CGSize)sizeWithString:(NSString *)string font:(UIFont *)font 2 3 { 4 CGRect rect = [string boundingRectWithSize:CGSizeMake(320, 8000)//限制最大的宽度和高度 5 options:NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesFontLeading |
NSStringDrawingUsesLineFragmentOrigin//采用换行模式 6 attributes:@{NSFontAttributeName: font}//传人的字体字典 7 context:nil]; 8 9 return rect.size; 10 }
方法二
1 CGRect contentRect = [NSString heightForString:badgeValue Size:contentSize Font:kValueFont]; 2 3 4 //获取某固定文本的显示高度 5 +(CGRect)heightForString:(NSString*)str Size:(CGSize)size Font:(UIFont*)font 6 { 7 return [NSString heightForString:str Size:size Font:font Lines:0]; 8 } 9 10 +(CGRect)heightForString:(NSString*)str Size:(CGSize)size Font:(UIFont*)font Lines:(NSInteger)lines 11 { 12 if (StringIsNullOrEmpty(str)) { 13 return CGRectMake(0, 0, 0, 0); 14 } 15 static UILabel *lbtext; 16 if (lbtext==nil) { 17 lbtext = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)]; 18 }else{ 19 lbtext.frame=CGRectMake(0, 0, size.width, size.height); 20 } 21 lbtext.font=font; 22 lbtext.text=str; 23 lbtext.numberOfLines=lines; 24 CGRect rect= [lbtext textRectForBounds:lbtext.frame limitedToNumberOfLines:lines]; 25 if(rect.size.height<0) 26 rect.size.height=0; 27 if (rect.size.width<0) { 28 rect.size.width=0; 29 } 30 return rect; 31 }
根据字符串的的长度来计算UITextView的高度
1 +(float)heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width 2 { 3 float height = [[NSString stringWithFormat:@"%@\n",value] boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize],NSFontAttributeName, nil] context:nil].size.height; 4 5 return height; 6 }
UITextView根据内容自动改变frame
1 -(void)textViewDidChange:(UITextView *)textView 2 { 3 [textView flashScrollIndicators]; // 闪动滚动条 4 static CGFloat maxHeight = 130.0f; 5 CGRect frame = textView.frame; 6 CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT); 7 CGSize size = [textView sizeThatFits:constraintSize]; 8 if (size.height >= maxHeight) 9 { 10 size.height = maxHeight; 11 textView.scrollEnabled = YES; // 允许滚动 12 } 13 else 14 { 15 textView.scrollEnabled = NO; // 不允许滚动,当textview的大小足以容纳它的text的时候,需要设置scrollEnabed为NO,否则会出现光标乱滚动的情况 16 } 17 textView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height); 18 }
浙公网安备 33010602011771号