ios - 检测何时停止在 UITextField 中输入

标签 ios objective-c uitextfield

我应该如何检测 UITextField 中的输入是否停止?我应该使用某种 UITextFieldTextDidEndEditingNotification 函数吗?我试图创建一个类似搜索的 instagram,它会在一秒钟不输入后显示结果。

最佳答案

我就是这样做的,它适用于 Swift 3

import UIKit

// don't forget to add UITextFieldDelegate
class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var textField: UITextField!

    var searchTimer: Timer?

    override func viewDidLoad() {
        super.viewDidLoad()

        // declare textField as delegate
        self.textField.delegate = self

        // handle the editingChanged event by calling (textFieldDidEditingChanged(-:))
        self.textField.addTarget(self, action: #selector(textFieldDidEditingChanged(_:)), for: .editingChanged)
    }

    // reset the searchTimer whenever the textField is editingChanged
    func textFieldDidEditingChanged(_ textField: UITextField) {

        // if a timer is already active, prevent it from firing
        if searchTimer != nil {
            searchTimer?.invalidate()
            searchTimer = nil
        }

        // reschedule the search: in 1.0 second, call the searchForKeyword method on the new textfield content
        searchTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(searchForKeyword(_:)), userInfo: textField.text!, repeats: false)
    }

    func searchForKeyword(_ timer: Timer) {

        // retrieve the keyword from user info
        let keyword = timer.userInfo!

        print("Searching for keyword \(keyword)")
    }

}

关于ios - 检测何时停止在 UITextField 中输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31227055/

相关文章:

ios - 动态编辑 3d touch 快捷方式列表

ios - 部分索引与搜索栏重叠(快速)

objective-c - UITableView 源代码 : Array of dictionaries

ios - 如何从嵌入在 Swift 中的 UITableView 中的文本字段中检索数据?

ios - Tesseract OCR w/iOS & Swift 返回错误或乱码

ios - 音频AVAssetWriter静音

objective-c - 如何使用 NSArray 和 NSDictionary?

使用 C++ 开发 iPhone 应用程序?

ios - 使用 Userattributes 更改 UITextField 的占位符文本颜色?

ios - 自定义单元格文本字段索引在滚动时发生变化