在UITextField外部点击时关闭键盘的最佳方法-iOS

时间:2018-08-05 02:41:01

标签: ios uitextfield swift4

我在这里找到了一些与此相关的主题,也有一些在线视频与此相关,但是每种解决方案似乎都存在其他问题。我找到的最简单的解决方案是以下解决方案。

    import UIKit

SignupController类:UIViewController,UITextFieldDelegate {

// Outlets
@IBOutlet weak var logoImage: UIImageView!
@IBOutlet weak var nameTF: CustomTextField!
@IBOutlet weak var emailTF: CustomTextField!
@IBOutlet weak var passwordTF: CustomTextField!
@IBOutlet weak var confirmPassTF: CustomTextField!

// Actions
@IBAction func signupButton(_ sender: UIButton) {
}


override func viewDidLoad() {
    super.viewDidLoad()
    logoImage.image = UIImage(named: "logo2")
    nameTF.delegate = self
    emailTF.delegate = self
    passwordTF.delegate = self
    confirmPassTF.delegate = self

}

// Moves to next text field each time return key is pressed
func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    if textField == nameTF {
        textField.resignFirstResponder()
        emailTF.becomeFirstResponder()
    } else if textField == emailTF {
        textField.resignFirstResponder()
        passwordTF.becomeFirstResponder()
    } else if textField == passwordTF {
        textField.resignFirstResponder()
        confirmPassTF.becomeFirstResponder()
    }else if textField == confirmPassTF {
        textField.resignFirstResponder()
    }
    return true
}



// Dismisses keyboard when tapped
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
}

}

它很有效,非常简单,但是我的项目和编码经验还处于起步阶段,所以我不确定这是不是最好的方法,仅仅是因为它很短,或者是否由于缺少它而缺少某些东西经验/知识?

任何人都知道更好的解决方案,或者这只是很好吗?

3 个答案:

答案 0 :(得分:0)

然后,您需要为此实现手势识别。或者,您可以这样做:

[tf.squeeze(v) 
    for v in tf.create_partitioned_variables(
        v.shape, [2, 1, 1], v)]

答案 1 :(得分:0)

我更喜欢使用UITextField委托方法:

 func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        view.endEditing(true)
        return true
    }

或设置具有“完成”或“退出”按钮的inputAccessoryView。

答案 2 :(得分:0)

只需这样做:

class viewController: UIViewController, UITextFieldDelegate {

// Outlets
@IBOutlet weak var logoImage: UIImageView!
@IBOutlet weak var nameTF: CustomTextField!
@IBOutlet weak var emailTF: CustomTextField!
@IBOutlet weak var passwordTF: CustomTextField!
@IBOutlet weak var confirmPassTF: CustomTextField!

// Actions
@IBAction func signupButton(_ sender: UIButton) {
}


override func viewDidLoad() {
    super.viewDidLoad()
    logoImage.image = UIImage(named: "logo2")
    nameTF.delegate = self
    emailTF.delegate = self
    passwordTF.delegate = self
    confirmPassTF.delegate = self
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dissMissKeyboard))
    view.addGestureRecognizer(tap)

}
func dissMissKeyboard() {
    view.endEditing(true)
}