IHaveAQuestion
IHaveAQuestion

Reputation: 839

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?

Upvotes: 9

Views: 8345

Answers (2)

Łukasz Przytuła
Łukasz Przytuła

Reputation: 575

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

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.

Upvotes: 9

jignesh Vadadoriya
jignesh Vadadoriya

Reputation: 3310

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

Upvotes: 1

Related Questions