简体   繁体   中英

Remove Top And Bottom Padding From A UILabel

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?

在此处输入图像描述

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.

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