简体   繁体   English

从 UILabel 中删除顶部和底部填充

[英]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.我有一个UILabel但由于某种原因它在顶部和底部有额外的填充。 I'd like the height of the label to be exactly the height of the text inside it.我希望 label 的高度恰好是其中文本的高度。

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.或者解决方案要求您在 VC 的layoutSubviews方法中调用某些内容,但我希望将所有视图代码存储在我的视图文件中。

Does anyone know how to fix this?有谁知道如何解决这一问题?

在此处输入图像描述

Call like;打电话喜欢;

let labelSize = UILabelWidthBasedOnTextLength(with: titleLabel) 

Then use like labelSize.width, to apply constraints.然后使用 labelSize.width 来应用约束。

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.也许这对任何新开发人员都有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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