iOS 11:UITextView typingAttributes在键入时重置

ht4b089n  于 2023-04-13  发布在  iOS
关注(0)|答案(5)|浏览(185)

我使用typingAttributes来设置新字体。在iOS 10上,一切正常,但在iOS 11上,第一个输入的字符是正确的,但属性被重置为以前的属性,第二个字符使用以前的字体输入。这是一个bug吗?我可以修复它吗?

bt1cpqcv

bt1cpqcv1#

为什么会这样:

Apple从iOS 11开始更新typingAttributes
此字典包含要应用于新键入文本的属性键(和相应值)。当文本视图的选择更改时,字典的内容将自动清除。

修复方法:

@Serdnad的代码可以工作,但它会跳过第一个字符。

1.如果您只想为文本视图提供一个通用类型属性

只需在此委托方法中设置一次typing属性,就可以使用此通用字体进行设置

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
}

czq61nw1

czq61nw12#

在使用typingAttributes时遇到内存使用问题
这一解决办法奏效了:

textField.defaultTextAttributes = yourAttributes // (set in viewDidLoad / setupUI)

使用typingAttributes有什么问题:在某个时间点,内存使用量上升,从未停止,并导致应用程序冻结。

vof42yt1

vof42yt13#

我遇到了同样的问题,最终通过在每次编辑后再次设置typingAttributes解决了这个问题。

*Swift 3酒店,纽约

func textViewDidChange(_ textView: UITextView) {
    NotesTextView.typingAttributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: UIFont.systemFont(ofSize: 17)]
}
nbysray5

nbysray54#

从iOS 11开始,苹果会在每个角色之后清除属性。
当文本视图的选择更改时,词典的内容将自动清除。
https://developer.apple.com/documentation/uikit/uitextview/1618629-typingattributes

lf3rwulv

lf3rwulv5#

2023,唯一的办法:

请注意,以前的解决方案(如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材料,而是视图材料。

在实践中,这样做:https://stackoverflow.com/a/75997746/294884并将其放入文本视图类中。

相关问题