在 Swift 中使用多行获取 UILabel 高度

Mer*_*nlı 4 uilabel ios swift swift2

我正在尝试计算 UILabel 的高度以使页面可滚动。标签包含用于显示 HTML 内容的属性文本。

我正在使用此函数将我的 HTML 内容获取到 UILabel:

func stringFromHTML( string: String?) -> NSAttributedString
{
    do{
        let pStyle = NSMutableParagraphStyle()
        pStyle.lineSpacing = 4
        pStyle.paragraphSpacingBefore = 10

        let str = try NSMutableAttributedString(data:string!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true
            )!, options:[NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSNumber(unsignedLong: NSUTF8StringEncoding)], documentAttributes: nil)
        str.addAttribute(NSParagraphStyleAttributeName, value: pStyle, range: NSMakeRange(0, str.length))
        str.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica Neue", size: 16.0)!, range: NSMakeRange(0, str.length))

        return str
    } catch
    {
        print("html error\n",error)
    }
    return NSAttributedString(string: "")
}
Run Code Online (Sandbox Code Playgroud)

我是新手。所以,我做了一个研究,找到了这个扩展来获得 UILabel 的高度。它返回一个值,但我想这不是真的。我的 UIScrollView 似乎不起作用:

extension UILabel{
    func requiredHeight() -> CGFloat{
        let label:UILabel = UILabel(frame: CGRectMake(0, 0, self.frame.width, CGFloat.max))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping
        label.font = self.font
        label.text = self.text

        label.sizeToFit()

        return label.frame.height
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我在 viewDidLoad() 方法中用于约束的代码:

// Set ContentView height
let activityTitleHeight:CGFloat = self.activityTitle.requiredHeight() + 20
let activityDescHeight:CGFloat = self.activityDesc.requiredHeight() + 20
let totalContentHeight:CGFloat = activityDescHeight + activityTitleHeight + 345
// There is an image view and a navigation, their total height: 345

let contentViewHeight:NSLayoutConstraint = NSLayoutConstraint(item: self.contentView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: totalContentHeight)
self.contentView.addConstraint(contentViewHeight)
Run Code Online (Sandbox Code Playgroud)

提前致谢!

ozg*_*gur 5

由于一旦 HTML 内容大于应用程序窗口的大小,您希望整个页面都可以滚动,因此我假设您的顶级视图是UIScrollView.

这里的主要技巧是设置显示 HTML 的标签的高度约束,0然后在计算它包含的 HTML 文本的高度后以编程方式更新它。

如果显示的文本太长,则滚动视图将自动开始滚动,前提是您正确设置了所有垂直约束。

顺便说一句,创建一个UILabel只是为了计算字符串的高度是一种矫枉过正。从 iOS7 开始,我们有NSAttributedString.boundingRect(size:options:context)方法计算使用给定选项绘制文本所需的最小矩形:

string.boundingRectWithSize(CGSizeMake(width, CGFloat.max), options: [.UsesFontLeading, .UsesLineFragmentOrigin], context: nil)
Run Code Online (Sandbox Code Playgroud)

回到你的问题,你应该创建一个NSLayoutConstraint代表标签高度的类型的 ivar :

class ViewController: UIViewController {
  @IBOutlet weak var htmlLabel: UILabel!
  private var labelHeightConstraint: NSLayoutConstraint!
  ...
Run Code Online (Sandbox Code Playgroud)

并将其constant属性设置0为我们之前所说的:

override func viewDidLoad() {
  super.viewDidLoad()
  ...

  htmlLabel.text = stringFromHTML(htmlText)

  labelHeightConstraint = NSLayoutConstraint(item: htmlLabel, attribute: .Height, relatedBy: .Equal,
                                             toItem: nil, attribute: .NotAnAttribute, multiplier: 0, constant: 0)
  scrollView.addConstraint(labelHeightConstraint)
}
Run Code Online (Sandbox Code Playgroud)

然后计算标签的高度:

(由于我们没有中任何超级视图的确切宽度viewDidLoad,因此viewDidAppear是进行此类计算的好地方。)

override func viewDidAppear(animated: Bool) {
  super.viewDidAppear(animated)

  let maxSize = CGSizeMake(CGRectGetWidth(scrollView.frame), CGFloat.max)
  let textSize = htmlLabel.attributedText!.boundingRectWithSize(maxSize, options: [.UsesFontLeading, .UsesLineFragmentOrigin], context: nil)

  labelHeightConstraint.constant = ceil(textSize.height)
}
Run Code Online (Sandbox Code Playgroud)

我为您创建了一个测试项目,展示了我在上面所做的工作。你可以从这里下载。