替换NSAttributedString中的整个文本字符串而不修改其他属性

Chi*_*ain 31 objective-c nsattributedstring ios

我有一个参考NSAttributedString,我想更改属性字符串的文本.

我想我必须创建一个新的NSAttributedString并使用这个新字符串更新引用.但是,当我这样做时,我失去了之前字符串的归属.

NSAttributedString *newString = [[NSAttributedString alloc] initWithString:text];
[self setAttributedText:newString];
Run Code Online (Sandbox Code Playgroud)

我参考了旧的属性字符串self.attributedText.如何保留新字符串中的先前属性?

Art*_*tal 36

您可以使用NSMutableAttributedString并只更新字符串,属性不会更改.例:

NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:@"my string" attributes:@{NSForegroundColorAttributeName: [UIColor blueColor], NSFontAttributeName: [UIFont systemFontOfSize:20]}];

//update the string
[mutableAttributedString.mutableString setString:@"my new string"];
Run Code Online (Sandbox Code Playgroud)


Sur*_*gch 31

迅速

在保留属性的同时更改文本:

let myString = "my string"
let myAttributes = [NSAttributedString.Key.foregroundColor: UIColor.blue, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 40)]
let mutableAttributedString = NSMutableAttributedString(string: myString, attributes: myAttributes)

let myNewString = "my new string"
mutableAttributedString.mutableString.setString(myNewString)
Run Code Online (Sandbox Code Playgroud)

结果mutableAttributedString

  • 在此输入图像描述
  • 在此输入图像描述

笔记

超出索引0的任何子范围的属性都将被丢弃.例如,如果我将另一个属性添加到原始字符串的最后一个单词,则在更改字符串后它将丢失:

// additional attribute added before changing the text
let myRange = NSRange(location: 3, length: 6)
let anotherAttribute = [ NSAttributedString.Key.backgroundColor: UIColor.yellow ]
mutableAttributedString.addAttributes(anotherAttribute, range: myRange)
Run Code Online (Sandbox Code Playgroud)

结果:

  • 在此输入图像描述
  • 在此输入图像描述

从中我们可以看到新字符串获取原始字符串索引0处的属性.实际上,如果我们调整范围

let myRange = NSRange(location: 0, length: 1)
Run Code Online (Sandbox Code Playgroud)

我们得到

  • 在此输入图像描述
  • 在此输入图像描述

也可以看看


小智 5

我做了一些扩展以使其变得非常简单:

import UIKit

extension UILabel {
    func setTextWhileKeepingAttributes(string: String) {
        if let newAttributedText = self.attributedText {
            let mutableAttributedText = newAttributedText.mutableCopy()

            mutableAttributedText.mutableString.setString(string)

            self.attributedText = mutableAttributedText as? NSAttributedString
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

https://gist.github.com/wvdk/e8992e82b04e626a862dbb991e4cbe9c

  • 我不得不这样写:`(mutableAttributedText as AnyObject).mutableString.setString(string)` (2认同)