如何在Swift中修复textView.resignFirstResponder()崩溃

时间:2019-06-08 16:39:59

标签: ios swift

一个非常简单的程序,它会弹出一个数字键盘,当用户单击该键盘时,我想将其关闭。

我有     ViewController:UIViewController,UITextFieldDelegate

inputField.delegate = self

inputField.resignFirstResponder() inside of touchesBegan

但是,每当我触摸数字键盘外部时,应用程序就会在模拟器中崩溃。

我尝试将inputField.resignFirstResponder()放在按钮动作中,该动作现在也触发崩溃(仅在首次提起数字键盘时)。

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        inputField.delegate = self
        // Do any additional setup after loading the view.
    }

    @IBOutlet weak var inputField: UITextField!
    @IBOutlet weak var outputLabel: UILabel!

    @IBAction func buttonPress(_ sender: UIButton) {
        inputField.resignFirstResponder()

        outputLabel.text = "Your stamp duty will be: £1,750"
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        inputField.resignFirstResponder()
    }
}

我在调试器中得到以下内容:

2019-06-08 17:23:19.945120+0100 StampDutyCalc[2104:180233] [MC] Reading from private effective user settings.

2019-06-08 17:23:19.976471+0100 StampDutyCalc[2104:180233] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitTruffle-NumberPad; using 20615_PortraitTruffle_iPhone-Simple-Pad_Default

2019-06-08 17:23:20.834475+0100 StampDutyCalc[2104:180233] -[StampDutyCalc.ViewController inputField:]: unrecognized selector sent to instance 0x7fb26c517040

2019-06-08 17:23:20.844880+0100 StampDutyCalc[2104:180233] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[StampDutyCalc.ViewController inputField:]: unrecognized selector sent to instance 0x7fb26c517040'

1 个答案:

答案 0 :(得分:0)

您可能不想覆盖touchesBegan。您可能只想使用UITapGestureRecognizer

这是我用来在用户点击其他位置时关闭键盘的扩展名:

extension UIViewController {
    /// Hides the keyboard when you tap anywhere in the view that doesnt have its own tap recognizer. Ex: the view behind a button or text field.
    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
}

现在只需致电:

MyViewController.hideKeyboardWhenTappedAround()

或者,您可以直接在VC上应用该代码,但是我喜欢使用扩展名以供重用。