Bounding rect of multiline string in UILabel swift

余生颓废 提交于 2020-12-03 03:40:50

问题


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.

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?

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

The code I have now is this:

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.

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


回答1:


Use:

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):

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.




回答2:


I think you need to Try this

    let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: _screenSize.width - 30, height: 5))
    messageLabel.font = self.txtDescription.font
    messageLabel.numberOfLines = 0
    messageLabel.text = "Your Massage"
    messageLabel.numberOfLines = 0
    messageLabel.sizeToFit()
    print(messageLabel.frame.size.height)

Remove all code Just try this Hope it will wirk



来源:https://stackoverflow.com/questions/41053018/bounding-rect-of-multiline-string-in-uilabel-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!