string 用另一个 NSAttributedString 替换 NSAttributedString 的子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8231240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:17:57  来源:igfitidea点击:

Replace substring of NSAttributedString with another NSAttributedString

stringcocoareplacensattributedstringfoundation

提问by Garoal

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

我想用另一个替换 a 的子字符串(例如@"replace")。NSAttributedStringNSAttributedString

I am looking for an equivalent method to NSString's stringByReplacingOccurrencesOfString:withString:for NSAttributedString.

我正在寻找与NSString's stringByReplacingOccurrencesOfString:withString:for等效的方法NSAttributedString

回答by Ole Begemann

  1. Convert your attributed string into an instance of NSMutableAttributedString.

  2. The mutable attributed string has a mutableStringproperty. According to the documentation:

    "The receiver tracks changes to this string and keeps its attribute mappings up to date."

    So you can use the resulting mutable string to execute the replacement with replaceOccurrencesOfString:withString:options:range:.

  1. 将您的属性字符串转换为NSMutableAttributedString.

  2. 可变属性字符串有一个mutableString属性。根据文档:

    “接收器跟踪对此字符串的更改并使其属性映射保持最新。”

    因此,您可以使用生成的可变字符串来执行替换replaceOccurrencesOfString:withString:options:range:

回答by Hashem Aboonajmi

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

以下是如何更改 NSMutableAttributedString 的字符串,同时保留其属性:

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:

目标-C:

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

回答by Darius Miliauskas

In my case, the following way was the only (tested on iOS9):

就我而言,以下方式是唯一的(在 iOS9 上测试过):

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];
    }

Of course it will be nice to find another better way.

当然,找到另一种更好的方法会很好。

回答by Imanou Petit

With Swift 4 and iOS 11, you can use one of the 2 following waysin order to solve your problem.

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



#1. Using NSMutableAttributedStringreplaceCharacters(in:with:)method

#1. 使用NSMutableAttributedStringreplaceCharacters(in:with:)方法

NSMutableAttributedStringhas a method called replaceCharacters(in:with:). replaceCharacters(in:with:)has the following declaration:

NSMutableAttributedString有一个方法叫做replaceCharacters(in:with:). replaceCharacters(in:with:)有以下声明:

Replaces the characters and attributes in a given range with the characters and attributes of the given attributed string.

用给定属性字符串的字符和属性替换给定范围内的字符和属性。

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

The Playground code below shows how to use replaceCharacters(in:with:)in order to replace a substring of an NSMutableAttributedStringinstance with a new NSMutableAttributedStringinstance:

下面的 Playground 代码显示了如何使用新实例replaceCharacters(in:with:)替换NSMutableAttributedString实例的子字符串NSMutableAttributedString

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. Using NSMutableStringreplaceOccurrences(of:with:options:range:)method

#2. 使用NSMutableStringreplaceOccurrences(of:with:options:range:)方法

NSMutableStringhas a method called replaceOccurrences(of:with:options:range:). replaceOccurrences(of:with:options:range:)has the following declaration:

NSMutableString有一个方法叫做replaceOccurrences(of:with:options:range:). replaceOccurrences(of:with:options:range:)有以下声明:

Replaces all occurrences of a given string in a given range with another given string, returning the number of replacements.

用另一个给定字符串替换给定范围内给定字符串的所有出现,返回替换次数。

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

The Playground code below shows how to use replaceOccurrences(of:with:options:range:)in order to replace a substring of an NSMutableAttributedStringinstance with a new NSMutableAttributedStringinstance:

下面的 Playground 代码显示了如何使用新实例replaceOccurrences(of:with:options:range:)替换NSMutableAttributedString实例的子字符串NSMutableAttributedString

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)

回答by gundrabur

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

迅速4:更新sunkas极好地解决迅速4和包裹在“扩展”。只需将其剪辑到您的 ViewController(在类之外)并使用它。

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
    }
}

回答by trickster77777

I had to bold text in <b>tags, here what I've done:

我不得不在<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;
}

回答by Chan Kai Long

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

回答by Sunkas

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:

我发现所有其他答案都不起作用。这是我在类别扩展中替换 NSAttributed 字符串内容的方法:

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
}

回答by Suresh Durishetti

I have a specific requirement and fixed like below. This might help someone.

我有一个特定的要求并修复如下。这可能会帮助某人。

Requirement:In the storyboard, rich text directly added to UITextView's attribute which contains a word "App Version: 1.0". Now I have to dynamise the version number by reading it from info plist.

要求:在storyboard中,直接在UITextView的属性中添加富文本,其中包含“App Version:1.0”字样。现在我必须通过从 info plist 读取它来动态化版本号。

Solution:Deleted version number 1.0 from the storyboard, just kept "App Version:" and added below code.

解决方案:从故事板中删除版本号 1.0,只保留“应用程序版本:”并添加以下代码。

NSAttributedString *attribute = self.firsttextView.attributedText;
NSMutableAttributedString *mutableAttri = [[NSMutableAttributedString alloc] initWithAttributedString:attribute];
NSString *appVersionText = @"App Version:";
if ([[mutableAttri mutableString] containsString:appVersionText]) {
    NSDictionary* infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString* version = [infoDict objectForKey:@"CFBundleShortVersionString"];
    NSString *newappversion = [NSString stringWithFormat:@"%@ %@",appVersionText,version] ;
    [[mutableAttri mutableString] replaceOccurrencesOfString:appVersionText withString:newappversion options:NSCaseInsensitiveSearch range:NSMakeRange(0, mutableAttri.length)];
    self.firsttextView.attributedText = mutableAttri;
}

Done!! Updated/modified attributedText.

完毕!!更新/修改的属性文本。