UIButton标题标签的大胆部分

问题描述 投票:0回答:2

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

谁有什么?

ios swift
2个回答
1
投票

除了一点点可以做的态度和一些肘部油脂之外别无他物。

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

0
投票

斯威夫特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!"

它工作正常

© www.soinside.com 2019 - 2024. All rights reserved.