0
我在S.O.上遇到過兩種不同的方法和擴展。無濟於事。有沒有一種明確的方式來只加粗UIButton.titleLabel的一部分?UIButton標題標籤的粗體部分
這些都是一些我已經試過了擴展:
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,但你應該能夠理解它仍然:http://stackoverflow.com/questions/17756067/ios-nsattributedstring-on-uibutton – believesInSanta