Replace substring of NSAttributedString with another NSAttributedString

前端 未结 9 1151
野趣味
野趣味 2020-12-01 08:51

I want to replace a substring (e.g. @\"replace\") of an NSAttributedString with another NSAttributedString.

I am looking for a

9条回答
  •  没有蜡笔的小新
    2020-12-01 09:41

    I find that all of the other answers does not work. Here is how I replaced content of a NSAttributed string in a category extension:

    func stringWithString(stringToReplace:String, replacedWithString newStringPart:String) -> NSMutableAttributedString
    {
        let mutableAttributedString = mutableCopy() as! NSMutableAttributedString
        let mutableString = mutableAttributedString.mutableString
    
        while mutableString.containsString(stringToReplace) {
            let rangeOfStringToBeReplaced = mutableString.rangeOfString(stringToReplace)
            mutableAttributedString.replaceCharactersInRange(rangeOfStringToBeReplaced, withString: newStringPart)
        }
        return mutableAttributedString
    }
    

提交回复
热议问题