[英]How do you clear attributes from NSMutableAttributedString?
如何將NSMutableAttributedString
中的所有屬性設置為NSMutableAttributedString
? 您是否必須枚舉並刪除它們?
我不想創建一個新的。 我正在處理textStorage
中的NSTextView
。 設置新字符串會重置NSTextView
的光標位置並觸發委托。
您可以像這樣刪除所有屬性:
NSMutableAttributedString *originalMutableAttributedString = //your string…
NSRange originalRange = NSMakeRange(0, originalMutableAttributedString.length);
[originalMutableAttributedString setAttributes:@{} range:originalRange];
請注意,這使用set Attributes (而不是add )。 從文檔:
這些新屬性替換了以前與
aRange
的字符關聯的任何屬性。
如果您需要有條件地執行其中任何一項操作,您還可以枚舉屬性並一一刪除它們:
[originalMutableAttributedString enumerateAttributesInRange:originalRange
options:kNilOptions
usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
[attrs enumerateKeysAndObjectsUsingBlock:^(NSString *attribute, id obj, BOOL *stop) {
[originalMutableAttributedString removeAttribute:attribute range:range];
}];
}];
根據文檔,這是允許的:
如果將此方法發送到
NSMutableAttributedString
的實例,則允許更改(刪除、添加或更改)。
如果string
是可變屬性字符串:
string.setAttributes([:], range: NSRange(0..<string.length))
如果你想枚舉條件刪除:
string.enumerateAttributesInRange(NSRange(0..<string.length), options: []) { (attributes, range, _) -> Void in
for (attribute, object) in attributes {
string.removeAttribute(attribute, range: range)
}
}
快速4:
我需要從可重用單元格中的 textview 中刪除屬性,如果另一個單元格使用 text 屬性,則它們會從一個單元格轉移到另一個單元格,因此文本只是具有前一個單元格屬性的文本。 受上述公認答案的啟發,只有這對我有用:
IOS
let attr = NSMutableAttributedString(attributedString: (cell.textView?.attributedText)!)
let originalRange = NSMakeRange(0, attr.length)
attr.setAttributes([:], range: originalRange)
cell.textView?.attributedText = attr
cell.textView?.attributedText = NSMutableAttributedString(string: "", attributes: [:])
cell.textView?.text = ""
蘋果系統
textView.textStorage?.setAttributedString(NSAttributedString(string: ""))
我如何在 tableView cellForRowAt indexPath 中刪除和添加字符串的屬性。 創建一個新的 NSMutableAttributedString 因為它是不可變的
// strike through on text
let attributeString = NSMutableAttributedString(string: "your string")
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
let removedAttributeString = NSMutableAttributedString(string: "your string")
removedAttributeString.removeAttribute(NSAttributedString.Key.strikethroughStyle, range: NSMakeRange(0, attributeString.length))
if (item.done == true) {
// applies strike through on text
cell.textLabel?.attributedText = attributeString
} else {
// removes strike through on text
cell.textLabel?.attributedText = removedAttributeString
}
NSAttributedString
是不可變的,因此您不能對它的實例做太多事情。 一種選擇是使用NSAttributedString
的string
屬性,用它創建一個新的NSMutableAttributedString
並應用所需的屬性或制作NSAttributedString
實例的mutableCopy
並修改范圍的當前屬性。
首先,它必須是一個 NSMutableAttributedString,因為它有 removeAttribute(name: String, range: NSRange) 的方法,是的,看起來你必須枚舉它們並刪除它們。
為什么不試試這種方法(Swift):
let s1 = <some NSAttributedString>
var s2 = NSMutableAttriutedString(string: s1.string())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.