UILabel Swift中多行字符串的边界矩形 [英] Bounding rect of multiline string in UILabel swift

查看:39
本文介绍了UILabel Swift中多行字符串的边界矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了几个小时,以在我拥有的UILabel中找到字符串的 boundingRect ,但是似乎没有任何效果.

I have been trying for hours now to find the boundingRect of a string in a UILabel I have, but nothing seems to be working.

据我了解, boundingRect 返回标签中实际文本的大小,而不是标签的大小或类似的大小.是真的,对吧?

From what I understand, boundingRect returns the size of the actual text in the label, not the label's size or something like that. This is true, right?

我有一个名为 messageLabel UILabel ,其中包含一些自动换行的文本.

I have a UILabel called messageLabel which contains some text that wraps to an unlimited number of lines.

我现在拥有的代码是:

let labelRect = (message as NSString).boundingRect(with: messageLabel.frame.size, 
    options: .usesLineFragmentOrigin, 
    attributes: [NSFontAttributeName : messageLabel.font], 
    context: nil)

不幸的是,这为我的文本返回了完全错误的尺寸.

Unfortunately, this returns totally wrong dimensions for my text.

在多行UILabel中返回文本尺寸的正确方法是什么?

What is the correct way to return the dimensions of text in a multiline UILabel?

推荐答案

使用:

let sizeToFit = CGSize(width: messageLabel.frame.size.width,
                       height: CGFloat.greatestFiniteMagnitude)
let textSize = messageLabel.sizeThatFits(sizeToFit)

无论如何,您的操作方式也应该正常工作(您可以在操场上看到两个函数返回的大小相同):

Anyway, the way you did it should work as well (you can see on playground both functions return same size):

我已经在操场上添加了一个示例视图,因此您可以看到,标签具有黑色边框,并且文本适合内部并且小于标签.Size可以在计算机上正常使用 sizeToFit boundingRect 方法(但 boundingRect 不会返回四舍五入的值).我已使用此计算出的大小在文本下方创建绿色背景视图,并且该文本适合它.

I've added a sample view to the playground, so you can see, the label has black border, and the text fits inside, and is smaller than label. Size is computer properly with both sizeToFit and boundingRect methods (but boundingRect returns not rounded values). I've use this computed size to create a green background view under the text, and it fits it properly.

这篇关于UILabel Swift中多行字符串的边界矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆