Ste*_*ley 4 xcode font-size ios nsmutableattributedstring swift
我已经看过这个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;
Run Code Online (Sandbox Code Playgroud)
我试图NSMutableAttributedString通过迭代每个属性来改变a中的字体.我很高兴听到有更好的方法,但如果有人能帮助我翻译上述内容,我会感到非常满意.
这是一个基本的实现.这对我来说似乎很简单,你没有提供你的尝试,所以我不确定你是否有类似的东西,它有问题,或者如果你刚刚接触Swift.
一个区别是这个实现使用了可选的cast(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()
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5399 次 |
| 最近记录: |