简体   繁体   English

不使用键盘快速键检测何时更改UITextField

[英]Detect when UITextField is changed not using the keyboard swift

I would like to know when the "text" property of myTextField, which is a subclass of UITextField, is cleared by my app. 我想知道我的应用何时清除了myTextField的“ text”属性(这是UITextField的子类)。 Since I have many textFields in my app I would like it to be a mechanism from within the subclass. 由于我的应用程序中有许多textField,因此我希望它是子类中的一种机制。

I found posts that suggest to use observer, and I tried it and it works but I would like a better way. 我发现了一些建议使用观察者的帖子,我尝试了一下,它可以工作,但是我想有一个更好的方法。

The problem with this method is that when I enter a single character using the keyboard and then I clear the "Text" from my app using 这种方法的问题是,当我使用键盘输入单个字符,然后使用以下命令清除应用中的“文本”时

someField.text = ""

the observer calls my app 50 times, which is very inefficient. 观察者调用我的应用程序50次,效率非常低。

Here is the code I use in myTextField class: 这是我在myTextField类中使用的代码:

addObserver(self, forKeyPath: "text", options: .New, context: nil)

and the function that gets the message is 得到消息的函数是

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if let newValue = change?[NSKeyValueChangeNewKey] {
        print("text changed: \(newValue)")
    }
}

The print() is called more than 50 times with "newValue" being empty ech time. print()被调用50次以上,其中“ newValue”为空ech时间。 Also, other textFields that has no data in their "text" property get called 5 times when I set their "text" property to "" from within my app, which is also inefficient. 另外,当我在我的应用程序中将其“ text”属性中没有数据的其他textFields设置为“”时,它们会被调用5次,这也是无效的。

Ignore my post. 忽略我的帖子。 I found my problem. 我发现了问题。 I put the "addObserver()" inside "editingRectForBounds()" thinking it is called only once upon initialisation, but found out that is called many times, so I had more than 50 "observers". 我将“ addObserver()”放在“ editingRectForBounds()”中,以为它在初始化时仅被调用一次,但是发现它被调用了很多次,所以我有50多个“观察者”。 Once I fixed it the app works as expected. 修复后,该应用程序将按预期运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM