将NSAttributedString的子串replace为另一个NSAttributedString

我想用另一个NSAttributedString @"replace"一个NSAttributedString的子string(例如@"replace" )。

我正在寻找一个等同的方法来NSStringstringByReplacingOccurrencesOfString:withString: NSAttributedString

  1. 将您的属性string转换为NSMutableAttributedString一个实例。

  2. 可变的属性string有一个mutableString属性。 根据文件:

    “接收者跟踪对此string的更改并保持其属性映射是最新的。”

    因此,您可以使用生成的可变string来执行replacereplaceOccurrencesOfString:withString:options:range:

这里是你如何改变NSMutableAttributedString的string,同时保留它的属性:

迅速:

 // 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"]; 

就我而言,以下方法是唯一的(在iOS9上testing):

 NSAttributedString *attributedString = ...; NSAttributedString *anotherAttributedString = ...; //the string which will replace while ([attributedString.mutableString containsString:@"replace"]) { NSRange range = [attributedString.mutableString rangeOfString:@"replace"]; [attributedString replaceCharactersInRange:range withAttributedString:anotherAttributedString]; } 

当然,find另一种更好的方法是很好的。

我不得不在<b>标签中加粗文字,这里是我所做的:

 - (NSAttributedString *)boldString:(NSString *)string { UIFont *boldFont = [UIFont boldSystemFontOfSize:14]; NSMutableAttributedString *attributedDescription = [[NSMutableAttributedString alloc] initWithString:string]; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@".*?<b>(.*?)<\\/b>.*?" options:NSRegularExpressionCaseInsensitive error:NULL]; NSArray *myArray = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)] ; for (NSTextCheckingResult *match in myArray) { NSRange matchRange = [match rangeAtIndex:1]; [attributedDescription addAttribute:NSFontAttributeName value:boldFont range:matchRange]; } while ([attributedDescription.string containsString:@"<b>"] || [attributedDescription.string containsString:@"</b>"]) { NSRange rangeOfTag = [attributedDescription.string rangeOfString:@"<b>"]; [attributedDescription replaceCharactersInRange:rangeOfTag withString:@""]; rangeOfTag = [attributedDescription.string rangeOfString:@"</b>"]; [attributedDescription replaceCharactersInRange:rangeOfTag withString:@""]; } return attributedDescription; } 
 NSMutableAttributedString *result = [[NSMutableAttributedString alloc] initWithString:@"I am a boy."]; [result addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, [result length])]; NSMutableAttributedString *replace = [[NSMutableAttributedString alloc] initWithString:@"a"]; [replace addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, [replace length])]; [result replaceCharactersInRange:NSMakeRange(5, [replace length]) withAttributedString:replace]; 

使用Swift 4和iOS 11,您可以使用以下两种方法之一来解决您的问题。


#1。 使用NSMutableAttributedString replaceCharacters(in:with:)方法

NSMutableAttributedString有一个名为replaceCharacters(in:with:)replaceCharacters(in:with:)具有以下声明:

将给定范围内的字符和属性replace为给定属性string的字符和属性。

 func replaceCharacters(in range: NSRange, with attrString: NSAttributedString) 

下面的Playground代码展示了如何使用replaceCharacters(in:with:)以便用新的NSMutableAttributedString实例replaceNSMutableAttributedString实例的子string:

 import UIKit // Set initial attributed string let initialString = "This is the initial string" let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red] let mutableAttributedString = NSMutableAttributedString(string: initialString, attributes: attributes) // Set new attributed string let newString = "new" let newAttributes = [NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue] let newAttributedString = NSMutableAttributedString(string: newString, attributes: newAttributes) // Get range of text to replace guard let range = mutableAttributedString.string.range(of: "initial") else { exit(0) } let nsRange = NSRange(range, in: mutableAttributedString.string) // Replace content in range with the new content mutableAttributedString.replaceCharacters(in: nsRange, with: newAttributedString) 

#2。 使用NSMutableString replaceOccurrences(of:with:options:range:)方法

NSMutableString有一个名为replaceOccurrences(of:with:options:range:)replaceOccurrences(of:with:options:range:)具有以下声明:

用给定的另一个stringreplace给定范围内给定string的所有匹配项,返回replace项的数目。

 func replaceOccurrences(of target: String, with replacement: String, options: NSString.CompareOptions = [], range searchRange: NSRange) -> Int 

下面的Playground代码显示了如何使用replaceOccurrences(of:with:options:range:)为了用新的NSMutableAttributedString实例replaceNSMutableAttributedString实例的子string:

 import UIKit // Set initial attributed string let initialString = "This is the initial string" let attributes = [NSAttributedStringKey.foregroundColor : UIColor.red] let mutableAttributedString = NSMutableAttributedString(string: initialString, attributes: attributes) // Set new string let newString = "new" // Replace replaceable content in mutableAttributedString with new content let totalRange = NSRange(location: 0, length: mutableAttributedString.string.count) _ = mutableAttributedString.mutableString.replaceOccurrences(of: "initial", with: newString, options: [], range: totalRange) // Get range of text that requires new attributes guard let range = mutableAttributedString.string.range(of: newString) else { exit(0) } let nsRange = NSRange(range, in: mutableAttributedString.string) // Apply new attributes to the text matching the range let newAttributes = [NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue] mutableAttributedString.setAttributes(newAttributes, range: nsRange) 

我发现所有其他答案都不起作用。 下面是我如何replace类别扩展中NSAttributedstring的内容:

 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 }