How can I concatenate NSAttributedStrings?

前端 未结 8 1359
野性不改
野性不改 2020-12-04 08:58

I need to search some strings and set some attributes prior to merging the strings, so having NSStrings -> Concatenate them -> Make NSAttributedString is not an option, is t

8条回答
  •  独厮守ぢ
    2020-12-04 09:52

    Swift 3: Simply create a NSMutableAttributedString and append the attributed strings to them.

    let mutableAttributedString = NSMutableAttributedString()
    
    let boldAttribute = [
        NSFontAttributeName: UIFont(name: "GothamPro-Medium", size: 13)!,
        NSForegroundColorAttributeName: Constants.defaultBlackColor
    ]
    
    let regularAttribute = [
        NSFontAttributeName: UIFont(name: "Gotham Pro", size: 13)!,
        NSForegroundColorAttributeName: Constants.defaultBlackColor
    ]
    
    let boldAttributedString = NSAttributedString(string: "Warning: ", attributes: boldAttribute)
    let regularAttributedString = NSAttributedString(string: "All tasks within this project will be deleted.  If you're sure you want to delete all tasks and this project, type DELETE to confirm.", attributes: regularAttribute)
    mutableAttributedString.append(boldAttributedString)
    mutableAttributedString.append(regularAttributedString)
    
    descriptionTextView.attributedText = mutableAttributedString
    

    swift5 upd:

        let captionAttribute = [
            NSAttributedString.Key.font: Font.captionsRegular,
            NSAttributedString.Key.foregroundColor: UIColor.appGray
        ]
    

提交回复
热议问题