将NSAttributedString的子字符串替换为另一个NSAttributedString

Gar*_*oal 52 string cocoa replace foundation nsattributedstring

我想将a的子串(例如@"replace")替换为NSAttributedString另一个子串NSAttributedString.

我在寻找一个相当于方法NSStringstringByReplacingOccurrencesOfString:withString:NSAttributedString.

Ole*_*ann 78

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

  2. 可变属性字符串具有mutableString属性.根据文件:

    "接收器跟踪对该字符串的更改并使其属性映射保持最新."

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

  • 这很好用,例如替换新的行字符:`[[result mutableString] replaceOccurrencesOfString:@"\n"withString:@""options:NSCaseInsensitiveSearch range:NSMakeRange(0,result.length)];` (6认同)
  • 方法"replaceOccurrencesOfString:withString:options:range:"适用于NSMutableString,不适用于NSAttributedString或NSMutableAttributedString.如果转换为NSMutableString在那里进行替换,则转换后将丢失其属性.问题是关于如何获得NSAttributedString作为结果,而不仅仅是字符串,所以答案是完全无关紧要的,但它得到了很多赞成. (4认同)

Has*_*jmi 19

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

迅速:

// 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")
Run Code Online (Sandbox Code Playgroud)

Objective-C的:

NSMutableAttributedString *newAttrStr = [attribtedTxt.mutableString setString:@"new string"];
Run Code Online (Sandbox Code Playgroud)


Dar*_*kas 18

在我的情况下,以下方式是唯一的(在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];
    }
Run Code Online (Sandbox Code Playgroud)

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

  • 这更适合替换给定范围内的字符串,而不是替换出现的字符串,因为字符串可能包含重复的子字符串。 (2认同)

Ima*_*tit 9

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


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

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

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

func replaceCharacters(in range: NSRange, with attrString: NSAttributedString)
Run Code Online (Sandbox Code Playgroud)

下面的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)
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

下面的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)
Run Code Online (Sandbox Code Playgroud)


tri*_*777 6

我不得不在<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;
}
Run Code Online (Sandbox Code Playgroud)


gun*_*bur 6

Swift 4: 更新了sunka对Swift 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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 好吧,你必须小心你所说的话,这里有很多开发人员学习坏习惯。如果您有 NSAttributedString 的扩展,请创建一个名为“NSAttributedString+Extensions.swift”的文件,并将其放入名为“Extensions”的文件夹中。 (3认同)