iOS – 如何在swift中使用`NSMutableString`
发布时间:2020-12-14 18:12:02 所属栏目:百科 来源:网络整理
导读:我已经看过这个Objective-C代码,但我很难在 swift中做同样的事情: NSMutableAttributedString *res = [self.richTextEditor.attributedText mutableCopy];[res beginEditing];__block BOOL found = NO;[res enumerateAttribute:NSFontAttributeName inRange
我已经看过这个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中的字体.我很高兴听到有更好的方法,但如果有人能帮助我翻译上述内容,我会感到非常满意. 解决方法
这是一个基本的实现.这对我来说似乎很简单,你没有提供你的尝试,所以我不确定你是否有类似的东西,它有问题,或者如果你刚刚接触Swift.
一个区别是这个实现使用可选的转换(如?),我这样做是为了演示这个概念.实际上,这不需要是可选的,因为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() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容