iOS-如何快速使用`NSMutableString` [英] iOS - How to use `NSMutableString` in swift

查看:98
本文介绍了iOS-如何快速使用`NSMutableString`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了这个Objective-C代码,但是我正在努力迅速地做到这一点:

I have seen this Objective-C code but I'm struggling to do the same in 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中的字体.我很高兴听到有一种更好的方法,但是如果有人可以帮助我翻译以上内容,我将不胜感激.

I'm trying to change the fonts in a NSMutableAttributedString by iterating over each of the attributes. I'm more than happy to hear that there is a better way but if anyone can help me translate the above I'd be more than greatful.

推荐答案

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

Here's a basic implementation. It seemed pretty straightforward to me, and you didn't provide your attempt, so I'm not sure if you have something similar and there's a problem with it, or if you're just new to Swift.

区别在于此实现使用可选的强制转换(as?),我已对此进行了演示.实际上,由于NSFontAttributeName可以保证提供UIFont,因此不必是可选的.

One difference is that this implementation uses optional casting (as?), which I did to demonstrate the concept. In practice, this doesn't need to be optional since NSFontAttributeName is guaranteed to provide a 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()

这篇关于iOS-如何快速使用`NSMutableString`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆