IOS - How to use `NSMutableString` in swift

I've seen this Objective-C code, but I'm trying 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;

      

I am trying to change fonts in NSMutableAttributedString

, iterating over each of the attributes. I am more than happy to hear that there is a better way, but if someone can help me translate the above, I would be more than great.

+3


source to share


2 answers


Here's a basic implementation. This seemed pretty straightforward to me and you haven't submitted your attempt, so I'm not sure if you have something like this and have a problem with it, or if you're just new to Swift.

One difference is that this implementation uses optional casting ( as?

), which I did to demonstrate the concept. In practice, this is not necessary as it is NSFontAttributeName

guaranteed to provide 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()

      

+6


source


Hope it helps!



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;

      

+5


source







All Articles