简体   繁体   中英

Bounding rect of multiline string in UILabel swift

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM