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

How to center UILabel text top and bottom spaces

我在表视图单元格中的内容视图的堆栈视图中有一个 UILabel。一切正常,单元格正在调整大小,但我无法在 UILabel 中将文本居中。我总是在文本底部有奇怪的空格。查看屏幕截图。

黄色:内容视图 绿色:堆栈视图 蓝色:标签

附加信息:单元格没有静态高度。黄色视图具有顶部底部和尾部和前导约束以及水平和垂直对齐到超级视图与堆栈视图相同的内容。我通过代码激活和停用的唯一具有恒​​定高度的是按钮。所以它根据单元格隐藏和显示。 Stackview 按比例填充。

UILabelsizeToFit

也尝试过:

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

里面的文字我解析为HTML

"<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>"

第二张截图

"<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>"

这是我用来解析 HTML

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), options: options, 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)
    }

}

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

if let attributedString = try? NSAttributedString(htmlString: htmlTxt, font: UIFont(name: "Avenir-Roman", size: CGFloat(Constants.defualtContentDescriptionFontSize)), useDocumentFontSize: false) {
        cell.detailLbl.attributedText = attributedString
}

部分问题是您使用的是 格式化 html 文本,其中包括“额外的 space”。

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

此代码创建两个 green-background 标签,每个标签的宽度相同,每个标签都没有高度限制:

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, constant: 40.0),
            secondLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            secondLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
            
        ])
        
        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, font: UIFont(name: "Avenir-Roman", size: 24.0), useDocumentFontSize: false) {
            secondLabel.attributedText = attributedString
            //cell.detailLbl.attributedText = attributedString
        }
    }

}

输出:

两者有什么区别?对于第二个标签,我在使用您的扩展程序处理 html 之前删除了 <p> </p> 标签。

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

同样,两者的区别在于我在处理 html.

之前删除了 h6 标签

您可能需要修改您的扩展以删除段落标签,或设置忽略它们的段落样式。