标签中属性文本的固有大小不正确

问题描述 投票:0回答:4

我对标签中的属性文本有疑问,该文本占用了底部的大量空间。当我使用未归属的尺寸时,尺寸是可以的,但现在我总是底部空间 - 在图像上标记为粉红色。我尝试在 Reveal.app 中更改高度约束的值(由 iOS 生成),当我将其设置为比实际小一点时,文本就会被截断。

我需要属性标签,因为我正在从 HTML 字符串创建属性:

<p style=\"font-family: EncodeSans-Thin; font-size: 10.0; color: #1f2e3b;\">
    Od 2004 roku wspieramy organizacje biznesowe w rozwoju sztuki zarządzania projektami. 
    Nasza działalność opiera się na trzech filarach – 
    <span style=\"font-family: EncodeSans-Light\">
        doradztwie, realizacji projektów na zlecenie oraz szkoleniach.
    </span>
</p>

你遇到过这样的问题吗?

更新:

我正在使用下面的函数从 HTML 字符串(作为字符串扩展)生成 NSAttributedString。

func makeAttributesFromHTML() -> NSAttributedString {
    guard let htmlData = self.dataUsingEncoding(NSUTF8StringEncoding) else {
        return NSAttributedString()
    }

    do {
        let atributedString = try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil)

        return atributedString
    } catch {
        return NSAttributedString()
    }
}
html ios autolayout uilabel nsattributedstring
4个回答
1
投票

我以前确实经历过这个。我发现一旦你在标签上设置了文本,你就必须使用

更新它
label.attributedText = foo;
[label setNeedsLayout]; // this line normally isn't required
[label layoutIfNeeded];

这应该将标签大小调整为正确的大小。如果失败,我不完全确定您的自动布局约束是如何设置的,但您可以手动计算标签的新高度并据此设置其高度约束。但这通常是没有必要的。

最后,文本末尾可能有尾随空格。如果您不需要,请务必将其删除。


1
投票

我发现从

<p>
内容中删除
HTML
标签可以修复大小。这让我认为,当
sizeToFit
方法必须处理从
HTML
创建的属性字符串中的段落时,它无法正确计算大小。

我知道这不是最好的解决方案,但也许您可以用

<p>
替换
<br>
标签。这是迄今为止我设法找到的唯一修复。


0
投票

这是因为

<p>
标签本质上会在末尾添加新行。一种方法是使用
<div style = display: inline>
这样就不会添加新行


0
投票

我遇到过类似的情况,我试图通过

NSMutableAttributedString
连接两个属性字符串。 所有
systemLayoutSizeFitting
sizeThatFits
intrinsicContentSize
UIlabel
boundingRect
NSAttributedString
都给出了错误的结果。

然后我注意到,对于其中一个字符串,我明确设置了属性

NSAttributedString.Key.paragraphStyle
,但对于另一个我没有。

当为两个字符串显式设置

NSAttributedString.Key.paragraphStyle
时,我已经解决了问题

© www.soinside.com 2019 - 2024. All rights reserved.