Make part of a UILabel bold in Swift

后端 未结 9 1958
面向向阳花
面向向阳花 2020-12-02 12:50

I have a UILabel I\'ve made programmatically as:

var label = UILabel()

I\'ve then declared some styling for the label, includi

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 13:41

    If you know which character place values you want to bold I created a function which takes ranges of characters and optional fonts (use nil if you just want to use the standard system font of size 12), and returns an NSAttributedString which you can attach to a label as its attributed text. I wanted to bolden the 0th, 10th, 22-23rd, 30th and 34th characters of my string so i used [[0,0], [10,10], [22,23], [30,30], [34,34]] for my boldCharactersRanges value.

    Usage:

    func boldenParts(string: String, boldCharactersRanges: [[Int]], regularFont: UIFont?, boldFont: UIFont?) -> NSAttributedString {
        let attributedString = NSMutableAttributedString(string: string, attributes: [NSAttributedString.Key.font: regularFont ?? UIFont.systemFont(ofSize: 12)])
        let boldFontAttribute: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: boldFont ?? UIFont.boldSystemFont(ofSize: regularFont?.pointSize ?? UIFont.systemFontSize)]
        for range in boldCharactersRanges {
            let currentRange = NSRange(location: range[0], length: range[1]-range[0]+1)
            attributedString.addAttributes(boldFontAttribute, range: currentRange)
            }
        return attributedString
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let label = UILabel()
        label.frame = CGRect(x: 0, y: 0, width: 180, height: 50)
        label.numberOfLines = 0
        label.center = view.center
        let text = "Under the pillow is a vogue article"
        let secretMessage = boldenParts(string: text, boldCharactersRanges: [[0,0], [10,10], [22,23], [30,30], [34,34]], regularFont: UIFont(name: "Avenir", size: 15), boldFont: UIFont(name: "Avenir-Black", size: 15))
        label.attributedText = secretMessage
        view.addSubview(label)
    }
    

提交回复
热议问题