【问题标题】:Get size of UILabel after setting text programmatically以编程方式设置文本后获取 UILabel 的大小
【发布时间】:2017-08-17 02:49:54
【问题描述】:

当为 UILabel 的文本属性设置一些字符串值时

var a : UILabel
a.text = "Variable length string"

autolayout 使用约束字体大小、标签行数等调整其大小。

问题是,如果我需要获取该标签的大小以便我可以(例如)决定包含该标签的表格单元格应该有多高,我应该在什么时候成功了吗?

尝试在不使用 UITableviewAutomaticDimension 的情况下解决此问题。

编辑:作为可能重复发布的答案有一些相似之处。但是,我的主要困惑是我可以在哪里成功且确定地提取 UILabel 的高度。

我多次尝试获取视图的大小,但返回的值不准确,需要以某种形式使用 viewDidLayoutSubviews()。我想我不太了解布局中发生的事情的顺序。 viewDidLoad() 和 awakeFromNib() 似乎也不同,但我可能对此有误。

如果有人能指出我理解这一点的正确方向,我将不胜感激

【问题讨论】:

标签: ios swift uitableview autolayout uilabel


【解决方案1】:

尝试在 ViewController 中使用 tableView 实现以下方法:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
             return HeightCalculator.height(with: text, inViewController: self)
}

然后添加以下类:

import UIKit

class HeightCalculator {
    let title: String
    let viewController: UIViewController

    class func height(with title: String, inViewController viewController: UIViewController) -> CGFloat {
        let calculator = HeightCalculator(title: title, viewController: viewController)

        return calculator.height
    }

    init(title: String, viewController: UIViewController) {
        self.title = title
        self.viewController = viewController
    }

    var height: CGFloat {
        let contentHeight = title.heightWithConstrainedWidth(width: defaultWidth, font: UIFont.preferredFont(forTextStyle: UIFontTextStyle.title1))
    }
}

你需要在你的字符串上添加以下扩展来获取高度:

import UIKit

extension String {
    func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return boundingBox.height
    }
}

使用heightForRowAt 计算高度,计算它的计算器类(contentHeight)和获取高度的扩展名。您可以调整计算器类以传递字体,以便它可以使用此字体将其传递给heightWithConstrainedWidth 方法。

【讨论】:

  • heightWithConstrainedWidth。肯定会加入我的扩展!谢谢
猜你喜欢
  • 2013-07-08
  • 1970-01-01
  • 2013-10-30
  • 2012-09-08
  • 1970-01-01
  • 1970-01-01
  • 2016-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多