我使用下面的代码从字符串长度计算标签的高度。我使用的是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有任何解决方案,请提供帮助。提前致谢
这里有一个用于计算iOS6和iOS7高度的解决方案,我通过了一些参数使其可重用。
#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;
}
希望这有所帮助,是的,任何建议都是值得赞赏的。快乐编码:)
对于iOS7及以上使用以下方法。
+ (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;
}
尝试使用此
#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;
sizeWithFont
已弃用。使用
[string sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}];
代替