【问题标题】:Making specific words in a title label bold in a UIButton in swift?快速在 UIButton 中将标题标签中的特定单词加粗?
【发布时间】:2022-01-20 04:11:54
【问题描述】:

我是 swift 的初学者,我发现 this StackOverflow questionthis StackOverflow question 对我的情况没有帮助,很可能是因为我对它的编码与他们不同(即 Swift,而不是 Obc)。

    private let createAccountButton: UIButton = {
        let button = UIButton()
        button.setTitleColor(.white, for: .normal)
        button.setTitle("dont have an account? sign up!", for: .normal) //line 4
        return button

我想要文本“注册!”在第 4 行中以粗体进行格式化,但在我目前的编码方式下没有找到任何可以支持它的在线内容。

【问题讨论】:

    标签: ios swift xcode


    【解决方案1】:

    使用按钮setAttributedTitle 属性设置属性文本。

    首先,创建属性文本。

    在这里,我为粗体属性文本创建了一个字符串扩展。返回属性文本并将此属性文本设置为按钮。

    extension String {
        /// Return attributed string
        /// - Parameter text: String text for bold text.
        func getAttributedBoldText(text: String) -> NSMutableAttributedString {
            let attributedString = NSMutableAttributedString(string: self, attributes: [.foregroundColor: UIColor.blue])
            if let range = self.range(of: text) {
                let startIndex = self.distance(from: self.startIndex, to: range.lowerBound)
                let range = NSMakeRange(startIndex, text.count)
                attributedString.addAttributes([.font : UIFont.boldSystemFont(ofSize: 20)], range: range)
            }
            return attributedString
        }
    }
    

    用法:

    private let createAccountButton: UIButton = {
        let button = UIButton()
        button.setTitleColor(.white, for: .normal)
        button.setAttributedTitle("dont have an account? sign up!".getAttributedBoldText(text: "sign up!"), for: .normal) // Here
        return button
    }()
    

    注意:根据您的布局修改扩展属性函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      相关资源
      最近更新 更多