How do you use NSAttributedString?

后端 未结 15 934
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 04:19

Multiple colours in an NSString or NSMutableStrings are not possible. So I\'ve heard a little about the NSAttributedString which was introduced wit

15条回答
  •  你的背包
    2020-11-22 04:45

    Swift 4

    let combination = NSMutableAttributedString()
    
    var part1 = NSMutableAttributedString()
    var part2 = NSMutableAttributedString()
    var part3 = NSMutableAttributedString()
    
    let attrRegular = [NSAttributedStringKey.font : UIFont(name: "Palatino-Roman", size: 15)]
    
    let attrBold:Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15)]
    
    let attrBoldWithColor: Dictionary = [NSAttributedStringKey.font : UIFont(name: "Raleway-SemiBold", size: 15),
                                     NSAttributedStringKey.foregroundColor: UIColor.red]
    
    if let regular = attrRegular as? [NSAttributedStringKey : NSObject]{
        part1 = NSMutableAttributedString(string: "first", attributes: regular)
    
    }
    if let bold = attrRegular as? [NSAttributedStringKey : NSObject]{
        part2 = NSMutableAttributedString(string: "second", attributes: bold)
    }
    
    if let boldWithColor = attrBoldWithColor as? [NSAttributedStringKey : NSObject]{
        part3 = NSMutableAttributedString(string: "third", attributes: boldWithColor)
    }
    
    combination.append(part1)
    combination.append(part2)
    combination.append(part3)
    

    Attributes list please see here NSAttributedStringKey on Apple Docs

提交回复
热议问题