【问题标题】:My return of height of a UILabel is never accurate我返回的 UILabel 高度永远不准确
【发布时间】:2016-03-24 00:12:46
【问题描述】:

我正在尝试捕获我的 UILabel 的高度,以便我可以动态设置它的单元格的高度,但它永远不会返回正确的高度,实际上,我的内容总是被截断并附加省略号。

我的代码:

let height   = String(page.valueForKey(subject)).heightWithConstrainedWidth(self.view.frame.width - 30, font: UIFont.systemFontOfSize(16.0))

// and at the bottom of my class..

// Custom functions
extension String {
    func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: CGFloat.max)
        let boundingBox = self.boundingRectWithSize(constraintRect, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
        return boundingBox.height
    }
}

这绝对是一次勇敢的尝试,因为它返回了某种相对较大的动态数字,但该数字总是很短且永远不准确。

我如何提取身高有什么明显不恰当的地方吗?有没有更好的方法来执行此操作?


根据马特的回复,我更新为这样测量标签:

// Custom functions
extension String {
    func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
        let label:UILabel = UILabel(frame: CGRectMake(0,0,width, CGFloat.max))
        label.numberOfLines = 0
        label.lineBreakMode = .ByWordWrapping
        label.font = font
        label.text = self
        label.sizeToFit()
        return label.frame.height
    }
}

但还是不够大..

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    您的代码适用于它的功能。问题仅仅是标签不是字符串。您正在查找字符串的高度。那不是你想做的。你想找到标签的高度!毕竟,UILabel 不仅仅是它包含的字符串。 UILabel 比字符串高。你没有考虑到这一点。

    【讨论】:

    • 致敬!这很有意义。我的印象是 cellForRowAtIndexPath (我在其中实例化我的 UILabel )被称为 after heightForRowAtIndexPath .. 我宁愿不实例化 UILabel 只是为了测量它,然后永远不要使用它,并稍后重新创建它。有没有办法将cellForRowAtIndexPath 的最终结果发送到heightForRowAtIndexPath 方法?我想我可以更新我的extension String 以返回 UILabel 中字符串的大小..
    • 那么问题实际上是您不知道如何根据其包含的标签来调整单元格的大小吗?也许这就是你应该问的!
    • 这是一个可下载的示例,其中包含具有不同高度标签的单元格。无需代码! github.com/mattneub/Programming-iOS-Book-Examples/tree/master/…
    • 啊,非常感谢!!超级欣赏你的作品。非常感谢!
    • 哇,这个解决方案太棒了。再次非常感谢。我只是能够击倒大量无用的代码!谢谢!!
    猜你喜欢
    • 2015-12-04
    • 1970-01-01
    • 2019-11-15
    • 2011-07-25
    • 1970-01-01
    • 2012-10-02
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多