简体   繁体   English

替换NSMutableAttributedString中的字符

[英]Replace character in NSMutableAttributedString

This works for a regular NSString : 这适用于常规NSString

NSString *newString = [myString stringByReplacingOccurrencesOfString:@"," withString:@""];

But there is no such method for NSMutableAttributedString . NSMutableAttributedString没有这样的方法。 How could I remove all instances of a comma in an NSMutableAttributedString ? 我怎样才能删除NSMutableAttributedString逗号的所有实例?

let attrString = NSMutableAttributedString(string: "Hello <b>friend<b>")

attrString.mutableString.replaceOccurrencesOfString("<b>", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: NSRange(location: 0, length: attrString.length))

Try this :) 试试这个 :)

Do it before you create the attributed string, if you can or depending on how you source it. 在创建属性字符串之前,如果可以或取决于您的来源,请执行此操作。 If you can't then you can use replaceCharactersInRange:withString: (or replaceCharactersInRange:withAttributedString: ), but you need to know the range so you need to search and iterate yourself. 如果你不能,那么你可以使用replaceCharactersInRange:withString:replaceCharactersInRange:withAttributedString: ,但你需要知道范围,所以你需要自己搜索和迭代。

NSString *newString= "I want to ,show, you how to achieve this";
NSMutableAttributedString *displayText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",newString]];
[[displayText mutableString] replaceOccurrencesOfString:@"," withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, displayText.string.length)];

You can initialize the attributed string with the stripped string with the designed init. 您可以使用设计的init初始化带有剥离字符串的属性字符串。 No? 没有?

The code could be applied from my answer here : 该代码可以从我的回答可以应用在这里

NSAttributedString *attributedString = ...;
NSAttributedString *anotherAttributedString = ...; //the string or characters which will replace

while ([attributedString.mutableString containsString:@"replace"]) {
        NSRange range = [attributedString.mutableString rangeOfString:@"replace"];
        [attributedString replaceCharactersInRange:range  withAttributedString:anotherAttributedString];
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM