如何居中UILabel文本顶部和底部空格

问题描述

我在表视图单元格中的内容视图的堆栈视图中有一个fruit country Apple UK 17.5 USA 49.5 Banana CANADA 28.5 UK 34.0 Grape UK 59.5 USA 33.0 Orange CANADA 65.0 USA 44.0 Pear UK 38.5 Plum USA 44.0 Tomato USA 65.0 。一切正常,单元格正在调整大小,但是我无法将文本放在UILabel中。我总是在文本的底部有奇怪的空格。查看屏幕截图。

黄色:内容视图 绿色:stackview 蓝色:标签

其他信息:单元格没有静态高度。黄色视图具有顶部,底部和尾部和前部约束,以及水平和垂直对齐以超级视图同一事物的堆栈视图。我通过代码激活和停用的唯一具有恒​​定高度的东西是按钮。因此,它会根据单元格进行隐藏和显示。 Stackview按比例填充。

UILabelUILabel

也尝试过:

sizetoFit

我里面的文本解析为 HTML

detailLbl.textAlignment = .center
detailLbl.lineBreakMode = .byWordWrapping //also tried byClipping
detailLbl.baselineAdjustment = .alignCenters

第二张屏幕截图

"<p><font color=\"#cd1719\">V/. </font>…The Word of the Lord.<br><b></b><font color=\"#cd1719\">R/. </font><b>Thanks be to God.</b></p>"

这是我用来解析HTML的"<h6 lang=\"en\" style=\"color=#cd1719 !important; font-weight: normal !important\"><font color=\"#cd1719\" weight=\"normal\"><i>The alleluia is said or sung.</i></font></h6>" 扩展名

NSAttributedString

这就是我在代码中使用它的方式

 extension NSAttributedString {

    convenience init(htmlString html: String,font: UIFont? = nil,useDocumentFontSize: Bool = true) throws {
        let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [
            .documentType: NSAttributedString.DocumentType.html,.characterEncoding: String.Encoding.utf8.rawValue
        ]

        let data = html.data(using: .utf8,allowLossyConversion: true)
        guard (data != nil),let fontFamily = font?.familyName,let attr = try? NSMutableAttributedString(data: data!,options: options,documentAttributes: nil) else {
            try self.init(data: data ?? Data(html.utf8),documentAttributes: nil)
            return
        }

        let fontSize: CGFloat? = useDocumentFontSize ? nil : font!.pointSize
        let range = NSRange(location: 0,length: attr.length)
        attr.enumerateAttribute(.font,in: range,options: .longestEffectiveRangeNotrequired) { attrib,range,_ in
            if let htmlFont = attrib as? UIFont {
                let traits = htmlFont.fontDescriptor.symbolicTraits
                var descrip = htmlFont.fontDescriptor.withFamily(fontFamily)

                if (traits.rawValue & UIFontDescriptor.SymbolicTraits.traitBold.rawValue) != 0 {
                    descrip = descrip.withSymbolicTraits(.traitBold)!
                }

                if (traits.rawValue & UIFontDescriptor.SymbolicTraits.traitItalic.rawValue) != 0 {
                    descrip = descrip.withSymbolicTraits(.traitItalic)!
                }
                
                attr.addAttribute(.font,value: UIFont(descriptor: descrip,size: fontSize ?? htmlFont.pointSize),range: range)
            }
        }

        self.init(attributedString: attr)
    }

}

enter image description here

enter image description here

解决方法

部分问题是您使用的是格式化格式的html文本,其中包括“多余的空格”。

例如,您的第一个html文本行包含<p> </p>标记。

此代码创建两个绿色背景标签,每个标签的宽度相同,每个标签都没有高度限制:

class ViewController: UIViewController,UIScrollViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let firstLabel = UILabel()
        firstLabel.backgroundColor = .green
        firstLabel.numberOfLines = 0
        firstLabel.translatesAutoresizingMaskIntoConstraints = false

        let secondLabel = UILabel()
        secondLabel.backgroundColor = .green
        secondLabel.numberOfLines = 0
        secondLabel.translatesAutoresizingMaskIntoConstraints = false
        
        view.addSubview(firstLabel)
        view.addSubview(secondLabel)

        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            
            // first label 40-pts from top,20-pts on each side
            firstLabel.topAnchor.constraint(equalTo: g.topAnchor,constant: 40.0),firstLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor,constant: 20.0),firstLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor,constant: -20.0),// second label 40-pts from bottom of first label,20-pts on each side
            secondLabel.topAnchor.constraint(equalTo: firstLabel.bottomAnchor,secondLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor,secondLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor,])
        
        var htmlTxt = "<p><font color=\"#cd1719\">V/. </font>…The Word of the Lord.<br><b></b><font color=\"#cd1719\">R/. </font><b>Thanks be to God.</b></p>"
        
        if let attributedString = try? NSAttributedString(htmlString: htmlTxt,font: UIFont(name: "Avenir-Roman",size: 24.0),useDocumentFontSize: false) {
            firstLabel.attributedText = attributedString
            //cell.detailLbl.attributedText = attributedString
        }

        htmlTxt = "<font color=\"#cd1719\">V/. </font>…The Word of the Lord.<br><b></b><font color=\"#cd1719\">R/. </font><b>Thanks be to God.</b>"
        
        if let attributedString = try? NSAttributedString(htmlString: htmlTxt,useDocumentFontSize: false) {
            secondLabel.attributedText = attributedString
            //cell.detailLbl.attributedText = attributedString
        }
    }

}

输出:

enter image description here

两者之间的区别?对于第二个标签,在处理带有扩展名的html之前,我删除了<p> </p>标签。

您的第二个html文本将其定义为h6 ...这是带有该字符串的输出:

enter image description here

同样,两者之间的区别是我在处理html之前删除了h6标签。

您可能需要修改扩展名以删除段落标记,或设置将其忽略的段落样式。