使用IOS 4,我想以编程方式理解给定文本是否适合某个UILabel,我可以在不进行复杂计算的情况下获得该信息吗?如果不是最基本的计算方法是什么?
答案 0 :(得分:8)
您可以在- (CGSize)sizeWithFont:(UIFont *)font
上致电NSString
。
答案 1 :(得分:6)
NSString方法sizeWithFont:contrainedToSize:lineBreakMode:可以提供帮助。它将为您提供计算出的字符串大小的CGSize。只需将其与您的UILabel.frame.size进行比较。
答案 2 :(得分:1)
要使用任何字体确定任何标签的高度,您可以使用此功能
+(float)calculateHeightOfTextFromWidth:(NSString *)text:(UIFont *)withFont:(float)width:(UILineBreakMode)lineBreakMode;
+(float) calculateHeightOfTextFromWidth:(NSString*) text: (UIFont*)withFont: (float)width:(UILineBreakMode)lineBreakMode
{
if (([text length]>0))
{
CGSize suggestedSize = [text sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode];
return suggestedSize.height;
}
return 18;
}
这是了解此功能工作的一个示例
if (![isRateABusinessController length]) {
companyNameLabel.text = [NSString stringWithFormat:@"%@",[allDetails objectForKey:@"CNAME"]];
NSString *cAdd = [NSString stringWithFormat:@"%@",[allDetails objectForKey:@"CADD"]];
float height = [ConfirmationViewController calculateHeightOfTextFromWidth:cAdd :[UIFont fontWithName:@"Arial" size:14] :170 :UILineBreakModeWordWrap];
addressLabel.text = [NSString stringWithFormat:@"%@",cAdd];
if (height > 30) {
CGRect rect = CGRectMake(addressLabel.frame.origin.x , addressLabel.frame.origin.y, addressLabel.frame.size.width, addressLabel.frame.size.height+12.0);
addressLabel.frame = rect;
}
}
else
{
companyNameLabel.text = [NSString stringWithFormat:@"%@",[Utility selectedCompanyName]];
NSString *cAdd = [NSString stringWithFormat:@"%@",[Utility selectedCompanyFullAddress]];
// NSString *star = [NSString stringWithFormat:@"Rating: %@",ratingName];
float height = [ConfirmationViewController calculateHeightOfTextFromWidth:cAdd :[UIFont fontWithName:@"Arial" size:14] :170 :UILineBreakModeWordWrap];
addressLabel.text = [NSString stringWithFormat:@"%@",cAdd];
if (height > 30) {
CGRect rect = CGRectMake(addressLabel.frame.origin.x , addressLabel.frame.origin.y, addressLabel.frame.size.width, addressLabel.frame.size.height+12.0);
addressLabel.frame = rect;
}
}
}