我所需要的就是遍历NSAttributedString
的所有属性并增加它们的字体大小。到目前为止,我已经成功地遍历和操作了属性,但不能保存回NSAttributedString
。我注释掉的那行对我不起作用。如何回存?
NSAttributedString *attrString = self.richTextEditor.attributedText;
[attrString enumerateAttributesInRange: NSMakeRange(0, attrString.string.length)
options:NSAttributedStringEnumerationReverse usingBlock:
^(NSDictionary *attributes, NSRange range, BOOL *stop) {
NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionaryWithDictionary:attributes];
UIFont *font = [mutableAttributes objectForKey:NSFontAttributeName];
UIFont *newFont = [UIFont fontWithName:font.fontName size:font.pointSize*2];
[mutableAttributes setObject:newFont forKey:NSFontAttributeName];
//Error: [self.richTextEditor.attributedText setAttributes:mutableAttributes range:range];
//no interfacce for setAttributes:range:
}];
发布于 2013-10-16 01:31:06
像这样的东西应该是有效的:
NSMutableAttributedString *res = [self.richTextEditor.attributedText mutableCopy];
[res beginEditing];
__block BOOL found = NO;
[res enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, res.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
if (value) {
UIFont *oldFont = (UIFont *)value;
UIFont *newFont = [oldFont fontWithSize:oldFont.pointSize * 2];
[res removeAttribute:NSFontAttributeName range:range];
[res addAttribute:NSFontAttributeName value:newFont range:range];
found = YES;
}
}];
if (!found) {
// No font was found - do something else?
}
[res endEditing];
self.richTextEditor.attributedText = res;
此时,res
有了一个新的属性字符串,所有字体的大小都是其原始大小的两倍。
发布于 2013-10-16 01:06:30
在开始之前,从原始的属性字符串创建一个NSMutableAttributedString
。在循环的每次迭代中,对可变属性字符串调用addAttribute:value:range:
(这将替换该范围内的旧属性)。
发布于 2019-02-05 05:29:54
这里是maddy的答案的一个快速端口(这对我来说非常有效!)。它被包装在一个小小的扩展中。
import UIKit
extension NSAttributedString {
func changeFontSize(factor: CGFloat) -> NSAttributedString {
guard let output = self.mutableCopy() as? NSMutableAttributedString else {
return self
}
output.beginEditing()
output.enumerateAttribute(NSAttributedString.Key.font,
in: NSRange(location: 0, length: self.length),
options: []) { (value, range, stop) -> Void in
guard let oldFont = value as? UIFont else {
return
}
let newFont = oldFont.withSize(oldFont.pointSize * factor)
output.removeAttribute(NSAttributedString.Key.font, range: range)
output.addAttribute(NSAttributedString.Key.font, value: newFont, range: range)
}
output.endEditing()
return output
}
}
https://stackoverflow.com/questions/19386849
复制相似问题