Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Top And Bottom Padding From A UILabel

Tags:

ios

uilabel

swift

I have a UILabel but it has extra padding on the top and bottom for some reason. I'd like the height of the label to be exactly the height of the text inside it.

I've been searching around on other questions and can't seem to find a solution that actually works. Or the solution requires you to call something in your layoutSubviews method of your VC, but I want all my view code to be stored in my view file.

Does anyone know how to fix this?

enter image description here

like image 681
cabyambo Avatar asked Dec 19 '25 08:12

cabyambo


1 Answers

Call like;

let labelSize = UILabelWidthBasedOnTextLength(with: titleLabel) 

Then use like labelSize.width, to apply constraints.

func UILabelWidthBasedOnTextLength(with label: UILabel) -> CGSize? {
        guard let text = label.text,
              let font = UIFont(name: label.font.fontName,
                                size: label.font.pointSize) else { return nil }

    var frame: CGRect = label.frame
    frame.size = text.size(withAttributes: [NSAttributedString.Key.font: font])
    return frame.size
}

This question asked very long ago, but I just wanted to contribute this approach. Maybe this will be usefull for any new developers.

like image 127
Yılmaz edis Avatar answered Dec 21 '25 22:12

Yılmaz edis