点击时隐藏 UIDatePicker

Hiding UIDatePicker when tapped around

我有一个 UIDatePicker,我想在点击按钮外部时隐藏它,就像关闭键盘一样,我已经尝试了所有方法,但似乎没有任何效果。

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var BDbtn: UIButton!


override func viewDidLoad() {
    super.viewDidLoad()

    datePicker.isHidden = true
    datePicker?.datePickerMode = .date
    let formatter = DateFormatter()
    formatter.dateFormat = "dd/MM/yyyy"
    BDbtn.setTitle("Pick a date!", for: .normal)
}
@IBAction func dateChanged(_ sender: Any) {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd/MM/yyyy"
    BDbtn.setTitle(formatter.string(from: datePicker.date), for: .normal)

}
@IBAction func BDpressed(_ sender: Any) {
    if datePicker.isHidden {
        datePicker.isHidden = false
    } else {
        datePicker.isHidden = true
    }
}

}

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

如果您在 Scrollview 或主 UIView 中添加了 datePicker。您可以使用 UITapGestureRecogniser 并在 taggesture 方法中添加一行代码:

self.view.endEditing(真)

就是这样。