我使用以下代码从字符串长度计算标签的高度。我使用的是xcode 5.0,它在iOS 6模拟器中运行良好,但在iOS 7中效果不佳。
NSString* str = [[array objectAtIndex:i]valueForKey:@"comment"];
CGSize size = [className sizeWithFont:[UIFont systemFontOfSize:15]
constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
Height_1 = size.height;
如果iOS 7有任何解决方案,那么请帮忙。 在此先感谢
答案 0 :(得分:21)
这里有一个我用来计算iOS 6和iOS 7高度的解决方案,我已经通过了一些参数来使它可以重复使用。
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
/**
* This method is used to calculate height of text given which fits in specific width having font provided
*
* @param text Text to calculate height of
* @param widthValue Width of container
* @param font Font size of text
*
* @return Height required to fit given text in container
*/
+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
{
CGFloat result = font.pointSize + 4;
if (text)
{
CGSize textSize = { widthValue, CGFLOAT_MAX }; //Width and height of text area
CGSize size;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
//iOS 7
CGRect frame = [text boundingRectWithSize:textSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{ NSFontAttributeName:font }
context:nil];
size = CGSizeMake(frame.size.width, frame.size.height+1);
}
else
{
//iOS 6.0
size = [text sizeWithFont:font constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
}
result = MAX(size.height, result); //At least one row
}
return result;
}
希望这会有所帮助,是的,任何建议都表示赞赏。快乐编码:)
对于iOS 7及以上版本,请使用以下方法。
+ (CGSize)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
CGSize size = CGSizeZero;
if (text) {
//iOS 7
CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:font } context:nil];
size = CGSizeMake(frame.size.width, frame.size.height + 1);
}
return size;
}
答案 1 :(得分:2)
尝试使用此
#define FONT_SIZE 15.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 20.0f
NSString *text;
CGSize constraint;
CGSize size;
CGFloat height;
text = [[array objectAtIndex:i]valueForKey:@"comment"];
constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGRect textRect = [text boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE]}
context:nil];
size = textRect.size;
height = size.height;
答案 2 :(得分:1)
sizeWithFont
已弃用。使用
[string sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}];
代替
答案 3 :(得分:-1)
使用以下代码获取标签的高度
CGSize szMaxCell = CGSizeMake(220, 2999);
UIFont *font = [UIFont systemFontOfSize:14.0f]; // whatever font you're using to display
CGSize szCell = [yourString sizeWithFont:font constrainedToSize:szMaxCell lineBreakMode:NSLineBreakByWordWrapping];