Make part of a UILabel bold in Swift

后端 未结 9 1973
面向向阳花
面向向阳花 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:30

    Just sharing my own quite-flexible implementation in Swift 4.0. Cause there are some requirements, like mine currently, that you need to set not only bold but italic the part of a label's text.

    import UIKit
    
    extension UILabel {
    
        /** Sets up the label with two different kinds of attributes in its attributed text.
         *  @params:
         *  - primaryString: the normal attributed string.
         *  - secondaryString: the bold or highlighted string.
         */
    
        func setAttributedText(primaryString: String, textColor: UIColor, font: UIFont, secondaryString: String, secondaryTextColor: UIColor, secondaryFont: UIFont) {
    
            let completeString = "\(primaryString) \(secondaryString)"
    
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.alignment = .center
    
            let completeAttributedString = NSMutableAttributedString(
                string: completeString, attributes: [
                    .font: font,
                    .foregroundColor: textColor,
                    .paragraphStyle: paragraphStyle
                ]
            )
    
            let secondStringAttribute: [NSAttributedStringKey: Any] = [
                .font: secondaryFont,
                .foregroundColor: secondaryTextColor,
                .paragraphStyle: paragraphStyle
            ]
    
            let range = (completeString as NSString).range(of: secondaryString)
    
            completeAttributedString.addAttributes(secondStringAttribute, range: range)
    
            self.attributedText = completeAttributedString
        }
    }
    

提交回复
热议问题