[英]Making specific words in a title label bold in a UIButton in swift?
[英]Bold part of a UIButton title label
在SO上遇到它們之后,我嘗試了幾種不同的方法和擴展,但均無濟於事。 有沒有確定的方法來僅加粗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)
}
}
有人有什么嗎
除了一點點可以做的姿勢和一些肘部潤滑脂,它什么也沒得到。
let text = "This is the"
let attr = NSMutableAttributedString(string: "\(text) button's text!")
attr.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(14), range: NSMakeRange(0, text.characters.count))
cell.nameLabel.setAttributedTitle(attr, forState: UIControlState.Normal)
// "**This is the** button's text!"
Swift 4版本的chicobermuda的答案 :
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!"
它工作正常
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.