How can I concatenate NSAttributedStrings?

前端 未结 8 1374
野性不改
野性不改 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:39

    If you're using Swift, you can just overload the + operator so that you can concatenate them in the same way you concatenate normal strings:

    // concatenate attributed strings
    func + (left: NSAttributedString, right: NSAttributedString) -> NSAttributedString
    {
        let result = NSMutableAttributedString()
        result.append(left)
        result.append(right)
        return result
    }
    

    Now you can concatenate them just by adding them:

    let helloworld = NSAttributedString(string: "Hello ") + NSAttributedString(string: "World")
    

提交回复
热议问题