4

我使用名为 demoLbl 的 OHAttributedLabel 来显示带有格式化区域的文本。此标签使用 Interface Builder 进行布局,并连接到我的 ViewController 中的一个属性。将属性文本设置为标签后,我希望所有文本都显示在标签中。
如果我不调整标签大小,则文本会在标签末尾被裁剪,因此其余文本将丢失。

如果我使用 [demoLbl sizeToFit]; 然后标签的高度大于或小于文本的高度(大约 10 点,随文本的长度而变化),因此在我的视图底部(滚动后)给我空白区域加上标签的宽度增加了大约2分。

如果我在将原始文本(NSString)放入 NSAttributedString 并将其添加到标签的属性文本属性之前计算原始文本(NSString)的高度,那么计算出的高度太小而无法将其设置为标签的高度。

有没有我可以应用的技巧或技巧,以便根据 NSAttributedString 的高度调整标签的高度?

PS:更具体地说,我想将 OHAttributedLabel 添加为标签,但我还不允许这样做。

4

3 回答 3

10

我是 OHattributedLabel 的作者。

我最近对我的大小计算做了一些修复。请检查一下,它可能会解决您的问题。

我还添加了一个名为sizeConstrainedToSize:fitRange:in的方法,NSAttributedString+Attributes.h该方法返回给定 NSAttributedString 的 CGSize(与 UIKit 的sizeWithFont:constrainedToSize:工作方式完全相同,但对于属性字符串和 CoreText 而不是 UIKit 的普通字符串)实际上 OHAttributedLabel 的 sizeThatFits: 现在自己调用此方法。

于 2011-08-22T06:34:00.350 回答
1

你可以看看这个类别是否给你一个更可靠的高度。 https://gist.github.com/1071565

用法

attrLabel.frame.size.height = [attrLabel.attributedString boundingHeightForWidth:attrLabel.frame.size.width];
于 2011-07-08T10:47:32.523 回答
1

我将此代码添加到 OHAttributedLabel 类的实现中:

// Toni Soler - 02/09/2011
// Overridden of the UILabel::sizeToFit method
- (void)sizeToFit
{
    // Do not call the standard method of the UILabel class, this resizes the frame incorrectly
    //[super sizeToFit];

    CGSize constraint = CGSizeMake(self.frame.size.width, 20000.0f);
    CGRect frame = self.frame;
    frame.size = [self sizeThatFits:constraint];
    [self setFrame:frame];
}
// End Toni Soler - 02/09/2011

感谢 Olivier 分享您的代码!

于 2011-09-02T10:28:33.663 回答