我用
typingAttributes
来设置新字体。在 iOS 10 上,一切正常,但在 iOS 11 上,第一个输入的字符是正确的,但随后属性被重置为以前的字符,第二个字符使用以前的字体输入。这是一个错误吗?我能以某种方式修复它吗?
苹果自 iOS 11 以来更新了
typingAttributes
本词典包含应用于新键入文本的属性键(和相应的值)。当文本视图的选择发生变化时,字典的内容会自动清除。
@Serdnad 的代码有效,但它会跳过第一个字符。这是我尝试所有可能想到的方法后的发现
1。如果您只想为文本视图使用一个通用的打字属性
只需在此委托方法中设置一次输入属性,您就可以使用这种单一的通用字体进行设置
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
//Set your typing attributes here
textView.typingAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.blue, NSAttributedStringKey.font.rawValue: UIFont.systemFont(ofSize: 17)]
return true
}
2。在我的例子中,富文本编辑器的属性一直在变化:
在这种情况下,我每次输入任何内容后都必须设置输入属性。感谢 iOS 11 的这次更新!
但是,与其在
textViewDidChange
方法中设置它,不如在 shouldChangeTextIn
方法中进行设置效果更好,因为它在将字符输入到文本视图之前被调用。
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
textView.typingAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.blue, NSAttributedStringKey.font.rawValue: UIFont.systemFont(ofSize: 17)]
return true
}
使用时内存使用有问题
typingAttributes
这个解决方案有效:
textField.defaultTextAttributes = yourAttributes // (set in viewDidLoad / setupUI)
使用 typingAttributes 有什么问题:在某个时间点,内存使用量上升并且从未停止并导致应用程序冻结。
我遇到了同样的问题,并最终通过在每次编辑后再次设置 typingAttributes 来解决它。
斯威夫特 3
func textViewDidChange(_ textView: UITextView) {
NotesTextView.typingAttributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: UIFont.systemFont(ofSize: 17)]
}
从 iOS 11 开始,Apple 清除每个字符后的属性。
当文本视图的选择发生变化时,字典的内容会自动清除。
https://developer.apple.com/documentation/uikit/uitextview/1618629-typingattributes
请注意,以前的解决方案(例如
textViewShouldBeginEditing
)根本行不通。你现在必须做这两个:
func textViewDidBeginEditing(_ textView: UITextView) {
_tvHassles()
outsideDelegate?.textViewDidBeginEditing?(textView)
}
func textViewDidChange(_ textView: UITextView) {
_tvHassles()
outsideDelegate?.textViewDidChange?(textView)
}
func _tvHassles() {
let ps = NSMutableParagraphStyle()
ps.lineSpacing = 3.0 // (means specifically "extra points between lines")
typingAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.green,
NSAttributedString.Key.font: UIFont. .. your font,
NSAttributedString.Key.tracking: 0.88,
NSAttributedString.Key.paragraphStyle: ps
]
}
在文本输入框中设置字体需要做这么多,这是完全荒谬的,但是,你已经做到了。
请注意,在现实生活中,在视图控制器中执行所有这些操作当然是疯狂的。 “设置字体”不是vc素材,是view素材
所以在实践中,这样做:https://stackoverflow.com/a/75997746/294884 并将其放入文本视图类中。