how to append Attributed Text String with Attributed String in Swift

后端 未结 4 1270
天涯浪人
天涯浪人 2021-01-31 01:52

I want to append an Attributed Text with another Attributed Text in Swift. Please provide any sample code for appending operation of two attributed String in Swift.

4条回答
  •  情话喂你
    2021-01-31 02:35

    @glace's answer, modified to avoid empty NSMutableAttributedString declaration. Valid in Swift 3.1:

    let yourAttributes = [NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont.systemFontOfSize(15)]
    let yourOtherAttributes = [NSForegroundColorAttributeName: UIColor.redColor(), NSFontAttributeName: UIFont.systemFontOfSize(25)]
    
    let partOne = NSMutableAttributedString(string: "This is an example ", attributes: yourAttributes)
    let partTwo = NSMutableAttributedString(string: "for the combination of Attributed String!", attributes: yourOtherAttributes)
    
    partOne.append(partTwo)
    

    partOne is then your final string with all the attributes. No intermediate "combiner" necessary.

    Swift 4

    let yourAttributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.black, .font: UIFont.systemFont(ofSize: 15)]
    let yourOtherAttributes: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.red, .font: UIFont.systemFont(ofSize: 25)]
    
    let partOne = NSMutableAttributedString(string: "This is an example ", attributes: yourAttributes)
    let partTwo = NSMutableAttributedString(string: "for the combination of Attributed String!", attributes: yourOtherAttributes)
    
    partOne.append(partTwo)
    

提交回复
热议问题