UIButton标题标签的大胆部分

时间:2016-01-23 02:42:04

标签: ios swift

在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)
                }
}

任何人都有什么?

2 个答案:

答案 0 :(得分:1)

除了一点点可以做的态度和一些肘部油脂之外什么都没有。

#spinning-circle img {
  width: 100%;
  height: auto;
}

答案 1 :(得分:0)

chicobermuda的answer的Swift 4版本:

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

工作正常