UIlabel NSMutableAttributedString 第二行在换行时不可见

UIlabel NSMutableAttributedString second line not visible upon line break

我正在尝试创建一个 UILabel,其中包含两个不同字体的文本,其中一个 NSMutableAttributedString 垂直位于另一个之上。在尝试通过 swift 的 \n 插入换行符时,我发现附加的字符串消失了。我已经尝试了各种 lineBreakMode 没有结果(有和没有 \n),同时通过设置大的 maximumLineHeight.

确保框架不会限制文本可见性

我还应该提到,根据 Apple 的文档,在将 UILabel.attributedText 设置为任何 NSAttributedText 实例时

When the label has an attributed string value, the system ignores the textColor, font, textAlignment, lineBreakMode, and lineBreakStrategy properties. Set the foregroundColor, font, alignment, lineBreakMode, and lineBreakStrategy properties in the attributed string instead.

这里是一些为了问题而简化的代码(我也试过在设置标签 attributedText 之后调用 .sizeTofit() 以及设置不同的 .lineBreakStrategys)

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
paragraphStyle.lineBreakMode = .byWordWrapping

let totalVisitsString = NSMutableAttributedString(string: "\(visitLogs.count)\n", attributes: [.font : UIFont.systemFont(ofSize: 25), .paragraphStyle : paragraphStyle])

totalVisitsString.append(NSMutableAttributedString(string: "Total visits", attributes: [.font : UIFont.systemFont(ofSize: 14)]))

totalVisitsLabel.attributedText = totalVisitsString

标签本身:

var totalVisitsLabel: UILabel = {
        let label = UILabel()
        
        label.translatesAutoresizingMaskIntoConstraints = false
        
        return label
    }()

默认情况下,您的标签 numberOfLines 是 1。您永远不会更改它,所以这就是您得到的。

标签创建时默认为 1 行。您需要将行数设置为 0(无限制)或您想要最大的任何数字。

var totalVisitsLabel: UILabel = {
    let label = UILabel()
    label.numberOfLines = 0
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()