iOS - 如何在Swift中使用`NSMutableString`

5
我看到了这段Objective-C代码,但我很难在Swift中实现相同的功能:
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;

我正在尝试通过迭代每个属性来更改NSMutableAttributedString中的字体。如果有更好的方法,我很乐意听取建议。如果有人可以帮助我翻译上述内容,我将不胜感激。

你能展示一下你目前的尝试吗?有什么问题出现了吗? - Aaron Brager
2个回答

6
这是一个基本的实现。对我来说似乎很简单,而且您没有提供您的尝试,所以我不确定您是否有类似的问题,或者您是新手。
一个区别是这个实现使用了可选的类型转换(as?),我这样做是为了演示概念。实际上,这不需要是可选的,因为NSFontAttributeName保证会提供一个UIFont
var res : NSMutableAttributedString = NSMutableAttributedString(string: "test");

res.beginEditing()

var found = false

res.enumerateAttribute(NSFontAttributeName, inRange: NSMakeRange(0, res.length), options: NSAttributedStringEnumerationOptions(0)) { (value, range, stop) -> Void in
    if let oldFont = value as? UIFont {
        let newFont = oldFont.fontWithSize(oldFont.pointSize * 2)
        res.removeAttribute(NSFontAttributeName, range: range)
        res.addAttribute(NSFontAttributeName, value: newFont, range: range)
        found = true
    }
}

if found == false {

}

res.endEditing()

5
希望这能帮到你!
var res : NSMutableAttributedString = self.richTextEditor.attributedText!
res.beginEditing()    
var found : bool = false;    
res.enumerateAttribute(NSFontAttributeName,inRange:NSMakeRange(0, res.length),options:0, usingBlock(value:AnyObject!, range:NSRange, stop:UnsafeMutablePointer<ObjCBool>) -> Void in {
    if (value) {
        let oldFont = value as UIFont;
        let newFont = oldFont.fontWithSize(oldFont.pointSize * 2)
        res.removeAttribute(NSFontAttributeName , range:range)
        res.addAttribute(NSFontAttributeName value:newFont range:range)
        found = true
    }
})
if !found {
    // No font was found - do something else?
}
res.endEditing()
self.richTextEditor.attributedText = res;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接