【问题标题】:Bold part of a UIButton title labelUIButton 标题标签的粗体部分
【发布时间】:2016-01-23 02:42:04
【问题描述】:

在 S.O. 上遇到它们后,我尝试了几种不同的方法和扩展。无济于事。是否有明确的方法仅将 UIButton.titleLabel 的一部分加粗?

这些是我尝试过的一些扩展:

func attributedText(fullStr: String, boldStr: String) -> NSAttributedString {

                let attributedString = NSMutableAttributedString(string: fullStr as String, attributes: [NSFontAttributeName:UIFont.systemFontOfSize(12.0)])

                let boldFontAttribute = [NSFontAttributeName: UIFont.boldSystemFontOfSize(12.0)]

                // Part of string to be bold
                attributedString.addAttributes(boldFontAttribute, range: NSMakeRange(0, boldStr.characters.count))


               return attributedString
}


func boldRange(range: Range<String.Index>) {
                if let text = self.attributedTitleForState(UIControlState.Normal) {
                    let attr = NSMutableAttributedString(attributedString: text)
                    let start = text.string.startIndex.distanceTo(range.startIndex)
                    let length = range.startIndex.distanceTo(range.endIndex)
                    attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(16)], range: NSMakeRange(start, length))
                    self.setAttributedTitle(attr, forState: UIControlState.Normal)
                }
}


func boldSubstring(substr: String) {
                let range = substr.rangeOfString(substr)
                if let r = range {
                    boldRange(r)
                }
}

有人有吗?

【问题讨论】:

  • 不清楚您的代码入口点在哪里,也不清楚您的NSAttributedString 对象是否在UIButton 上正确设置。这是关于如何使用它的示例。它是 Obj-C 但你应该仍然能够理解它:stackoverflow.com/questions/17756067/…
  • 在另一个 post 中找到了有效的答案。

标签: ios swift


【解决方案1】:

Swift 4 版本的 chicobermuda 的 answer:

let text = "This is the"
let attr = NSMutableAttributedString(string: "\(text) button's text!")
attr.addAttribute(NSAttributedStringKey.font, value: UIFont.boldSystemFont(ofSize: 14), range: NSMakeRange(0, text.count))
cell.nameLabel.setAttributedTitle(attr, forState: .normal)

// "**This is the** button's text!"

效果很好

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    相关资源
    最近更新 更多