Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bounding rect of multiline string in UILabel swift

Tags:

ios

swift

swift3

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?

like image 834
IHaveAQuestion Avatar asked Dec 09 '16 04:12

IHaveAQuestion


2 Answers

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.

like image 175
Łukasz Przytuła Avatar answered Nov 10 '22 13:11

Łukasz Przytuła


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

like image 1
jignesh Vadadoriya Avatar answered Nov 10 '22 12:11

jignesh Vadadoriya