Swift 5 将 alpha 添加到带有属性文本的 UILabel

Swift 5 Add alpha to UILabel with attributed text

我有一个 UILabel,它通过 属性文本 .

合并了两个不同的 strings/font

我想在 UILabel 的 attrs2 上加入一个 alpha。但是让字符串的第一部分没有字母。

代码:

    private let titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = .black
        label.textAlignment = .center
        let attrs1 = [NSAttributedString.Key.font : UIFont(name:"SFMono-Bold", size: 20)]

        let attrs2 = [NSAttributedString.Key.font : UIFont.sfMonoMedium(ofSize: 20)]

        let attributedString1 = NSMutableAttributedString(string:"Fast credit card\n payments", attributes:attrs1 as [NSAttributedString.Key : Any])

        let attributedString2 = NSMutableAttributedString(string:" using Square.", attributes:attrs2 as [NSAttributedString.Key : Any])

        attributedString1.append(attributedString2)
        label.attributedText = attributedString1

        return label
    }()

伪:

let attrs2 = [NSAttributedString.Key.font : UIFont.sfMonoMedium(ofSize: 20), NSAttributedString.Key.font.alpha..... : 0.75]

attrs2.alpha = 0.75

您可以使用 .foregroundColor 属性来做到这一点。

let attrs2: [NSAttributedString.Key: Any] = [
    .font : UIFont.sfMonoMedium(ofSize: 20),
    .foregroundColor: UIColor.black.withAlphaComponent(0.5),
]