Replace substring of NSAttributedString with another NSAttributedString

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

    Here is how you can change the string of NSMutableAttributedString, while preserving its attributes:

    Swift:

    // first we create a mutable copy of attributed text 
    let originalAttributedText = nameLabel.attributedText?.mutableCopy() as! NSMutableAttributedString
    
    // then we replace text so easily
    let newAttributedText = originalAttributedText.mutableString.setString("new text to replace")
    

    Objective-C:

    NSMutableAttributedString *newAttrStr = [attribtedTxt.mutableString setString:@"new string"];
    

提交回复
热议问题