选择预测文本并将其添加到文本时,不会触发iOS textViewDidChange

时间:2016-08-01 00:53:01

标签: ios swift keyboard uitextview

enter image description here

当我点击“Hello”或“He”时,不会触发textViewDidChange。

如何检测何时选择预测文本?

4 个答案:

答案 0 :(得分:1)

尝试使用shouldChangeTextInRange代替textViewDidChange 我尝试了它,它是用预测文本触发的

答案 1 :(得分:0)

您是否设置了textView.delegate?

答案 2 :(得分:0)

  1. YourViewController<UITextViewDelegate>
  2. 设置textView后,textView.delegate = self
  3. func textViewDidChange(textView: UITextView) func textViewDidChange(textView: UITextView) { //textView(Sender) if(textView == yourtextview) { //do something } }

答案 3 :(得分:0)

当UITextView更改时,我必须使用NotificationCenter来获得通知。 我创建了UITextView的扩展以注册/注销这些通知。请记住,当您不再希望继续处理这些更改时(例如,在viewWillDisappear上,请致电取消注册。

import UIKit

extension UITextView {

    public func registerTextViewNotifications() {
        let center = NotificationCenter.default
        center.addObserver(self,
                           selector: #selector(textViewDidChangeWithNotification(_:)),
                           name: UITextView.textDidChangeNotification,
                           object: nil)
    }

    public func unregisterTextViewNotifications() {
        let center = NotificationCenter.default
        center.removeObserver(self,
                              name: UITextView.textDidChangeNotification,
                              object: nil)
    }

    @objc private func textViewDidChangeWithNotification(_ notification: Notification) {
        // Do something when edited
        print("Text: \(String(describing: text))")
    }

}

class ViewController: UIViewController {

    @IBOutlet var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        textView.registerTextViewNotifications()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        textView.unregisterTextViewNotifications()
    }

}