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

时间:2011-11-22 17:43:38

标签: string cocoa replace nsattributedstring foundation

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

我正在为NSString寻找NSAttributedString stringByReplacingOccurrencesOfString:withString:的等效方法。

9 个答案:

答案 0 :(得分:76)

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

  2. 的实例
  3. 可变属性字符串具有mutableString属性。根据文件:

      

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

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

答案 1 :(得分: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")

<强>目标-C:

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

答案 2 :(得分: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];
    }

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

答案 3 :(得分: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)

下面的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。使用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

下面的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)

答案 4 :(得分: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;
}

答案 5 :(得分:4)

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

答案 6 :(得分:3)

快捷键4:sunkas更新为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
    }
}

答案 7 :(得分:2)

我发现所有其他答案都不起作用。以下是我如何替换类别扩展中的NSAttributed字符串的内容:

<div class="container">
  <div id="left">
     blah blah balah blah blah.......
   </div>

  <div id="right">
    <fieldset class="form">
            <legend class="fit-title-blackgrad">Defaulter List Selection</legend>
            <div>
                <label class="form-label">Select Semester</label>
                <select class="form-input selecttodiv" name="dsem" id="dsem" tabindex="1" required=""><option value="">------</option><option value="I">I</option><option value="II">II</option><option value="III">III</option><option value="IV">IV</option><option value="V">V</option><option value="VI">VI</option><option value="VII">VII</option><option value="VIII">VIII</option>                </select>
            </div>
            <div>
                <label class="form-label">From (Month)</label>
                <select class="form-input" name="dfmonth" id="dfmonth" tabindex="2" required=""><option value="">------</option><option value="7">July</option>            </select>
            </div>
            <div>
                <label class="form-label">Cut-Off Percentage........................</label>
                <input class="form-input" type="number" min="50" max="75" name="dcutoff" id="dcutoff" tabindex="4" value="75" required="">
                
            </div>
            <div>
                <input type="submit" class="button form-button" value="Load">
            </div>
                    
           </fieldset>
  
    </div>
  </div>

答案 8 :(得分:2)

我有一个具体要求,并按如下所示进行修复。这可能会对某人有所帮助。

要求:在情节提要中,富文本直接添加到UITextView的属性中,其中包含单词“ App Version:1.0”。现在,我必须通过从信息plist读取版本号来对其进行动态化。

解决方案: 从情节提要中删除了版本号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;
}

完成!!更新/修改了attributedText。