【问题标题】:iOS - How to use `NSMutableString` in swiftiOS - 如何在 swift 中使用`NSMutableString`
【发布时间】:2014-12-20 16:31:27
【问题描述】:

我已经看过这段 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 中的字体。我很高兴听到有更好的方法,但如果有人能帮我翻译以上内容,我会非常感激。

【问题讨论】:

  • 你能展示你到目前为止的尝试吗?什么不工作?

标签: ios xcode swift font-size nsmutableattributedstring


【解决方案1】:

这是一个基本的实现。这对我来说似乎很简单,而且你没有提供你的尝试,所以我不确定你是否有类似的东西并且有问题,或者你是否只是 Swift 的新手。

一个区别是这个实现使用了可选转换 (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()

【讨论】:

    【解决方案2】:

    希望对你有帮助!

    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;
    

    【讨论】:

      猜你喜欢
      • 2017-06-21
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多