[英]Swift - Attributed Text features using Storyboard all reset when setting font size programmatically and run simulator
On the storyboard I created a text view.在故事板上,我创建了一个文本视图。 Inserted two paragraphs of text content inside textview.在 textview 中插入了两段文本内容。 Selected custom attributes on the storyboard and made some words bold.在故事板上选择自定义属性并加粗一些文字。 When I run the simulator, everything is ok.当我运行模拟器时,一切正常。 But when I set the font size programmatically with respect to the "view.frame.height", the bold words which I set on the storyboard resets to regular words.但是当我相对于“view.frame.height”以编程方式设置字体大小时,我在故事板上设置的粗体字会重置为常规字词。
Code: "abcTextView.font = abcTextView.font?.withSize(self.view.frame.height * 0.021)"代码:“abcTextView.font = abcTextView.font?.withSize(self.view.frame.height * 0.021)”
I couldn't get past this issue.我无法解决这个问题。 How can I solve this?我该如何解决这个问题?
The problem is that you're working with an AttributedString.问题是您正在使用 AttributedString。 Take a look at Manmal's excellent answer here if you want more context, and an explanation of how the code works:如果您需要更多上下文,请在此处查看 Manmal 的出色回答,并解释代码的工作原理:
NSAttributedString, change the font overall BUT keep all other attributes? NSAttributedString,整体更改字体但保留所有其他属性?
Here's an easy application of the extension he provides, to put it in the context of your problem:这是他提供的扩展的一个简单应用,将其放在您的问题的上下文中:
class ViewController: UIViewController {
@IBOutlet weak var myTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let newString = NSMutableAttributedString(attributedString: myTextView.attributedText)
newString.setFontFace(font: UIFont.systemFont(ofSize: self.view.frame.height * 0.033))
myTextView.attributedText = newString
}
}
extension NSMutableAttributedString {
func setFontFace(font: UIFont, color: UIColor? = nil) {
beginEditing()
self.enumerateAttribute(
.font,
in: NSRange(location: 0, length: self.length)
) { (value, range, stop) in
if let f = value as? UIFont,
let newFontDescriptor = f.fontDescriptor
.withFamily(font.familyName)
.withSymbolicTraits(f.fontDescriptor.symbolicTraits) {
let newFont = UIFont(
descriptor: newFontDescriptor,
size: font.pointSize
)
removeAttribute(.font, range: range)
addAttribute(.font, value: newFont, range: range)
if let color = color {
removeAttribute(
.foregroundColor,
range: range
)
addAttribute(
.foregroundColor,
value: color,
range: range
)
}
}
}
endEditing()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.