我正在尝试测量 NSString 的视觉大小,它考虑了我可以呈现的行数。但是, sizeWithFont 没有考虑 numberOfLines 属性?所以我的布局算法将所有内容定位在低于实际需要的位置。
_price = [[UILabel alloc] init];
_price.text = myPriceValue;
_price.lineBreakMode = UILineBreakModeWordWrap;
_price.numberOfLines = 3;
_price.backgroundColor = [UIColor clearColor];
_price.textColor = TTSTYLEVAR(colorPrice);
/// the follow code ignores numberOfLines and just tells me the size of the whole block.
// I'd like it to be aware of numberOfLines
//
CGSize priceSize = [_price.text sizeWithFont:_price.font
constrainedToSize:CGSizeMake(maxWidth, CGFLOAT_MAX)
lineBreakMode:UILineBreakModeWordWrap];
有谁知道如何使用 iPhone SDK 执行此操作?
最佳答案
不要使用 CGFLOAT_MAX 作为文本计算的最大高度,尝试使用以下方法获取一行的大小:
[_price.text sizeWithFont:_price.font].height
然后将其乘以您想要的最大行数,然后将其代入您限制自己的尺寸的高度。它可能看起来像这样:
_price = [[UILabel alloc] init];
_price.text = myPriceValue;
_price.lineBreakMode = UILineBreakModeWordWrap;
_price.numberOfLines = 3;
_price.backgroundColor = [UIColor clearColor];
_price.textColor = TTSTYLEVAR(colorPrice);
CGFloat lineHeight = [_price.text sizeWithFont:_price.font].height;
CGSize priceSize = [_price.text sizeWithFont:_price.font
constrainedToSize:CGSizeMake(maxWidth, lineHeight * _price.numberOfLines)
lineBreakMode:UILineBreakModeWordWrap];
如果您将行数设置为 0,请不要使用此选项,因为在这种情况下您的最大高度将为 0;那么你应该使用 CGFLOAT_MAX。
关于iPhone UILabel sizeWithFont :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1204000/