boundingRectWithSize总是返回相同的CGRect

时间:2017-04-23 14:07:47

标签: ios objective-c

我正在尝试获取NSString的子字符串,该子字符串可以放入UILabel的框架中。我正在使用此代码来获取CGRect -

CGSize  sizeConstraint = CGSizeMake(355, 293.09375);

NSMutableParagraphStyle *paraStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paraStyle.lineBreakMode = NSLineBreakByWordWrapping;

NSDictionary *attributes = @{ NSFontAttributeName : bodyFont, NSParagraphStyleAttributeName : paraStyle};

NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:body attributes:attributes];
CGRect boundingRect = [attributedText boundingRectWithSize:sizeConstraint options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) context:nil];

我面临的问题是boundingRectWithSize在字符串中的一定数量的字符后返回相同的CGRrect。这是字符串长度为677个字符时得到的CGRect -

(CGRect) boundingRect = (origin = (x = 0, y = 0), size = (width = 352.515625, height = 281.25))

当字符串长度为1354个字符时,我得到CGRect -

(CGRect) boundingRect = (origin = (x = 0, y = 0), size = (width = 352.515625, height = 281.25))

不知道为什么

1 个答案:

答案 0 :(得分:0)

刚刚意识到我的错误 -

CGSize  sizeConstraint = CGSizeMake(355, 293.09375);

应该是

CGSize  sizeConstraint = CGSizeMake(labelWidth, CGFLOAT_MAX);

然后我应该研究修剪字符串的逻辑。笨!