Replace substring of NSAttributedString with another NSAttributedString

前端 未结 9 1119
野趣味
野趣味 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:23

    Swift 4: Updated sunkas excellent solution to Swift 4 and wrapped in "extension". Just clip this into your ViewController (outside the class) and use it.

    extension NSAttributedString {
        func stringWithString(stringToReplace: String, replacedWithString newStringPart: String) -> NSMutableAttributedString
        {
            let mutableAttributedString = mutableCopy() as! NSMutableAttributedString
            let mutableString = mutableAttributedString.mutableString
            while mutableString.contains(stringToReplace) {
                let rangeOfStringToBeReplaced = mutableString.range(of: stringToReplace)
                mutableAttributedString.replaceCharacters(in: rangeOfStringToBeReplaced, with: newStringPart)
            }
            return mutableAttributedString
        }
    }
    

提交回复
热议问题