Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Đóng Alert khi tap ra ngoài vùng Alert trong iOS

Mặc định UIAlertController không tự dismiss khi tap ngoài. Cách xử lý:

  1. Tạo UIAlertController style .alert.
  2. Present kèm completion block: bật isUserInteractionEnabled cho superview, gán UITapGestureRecognizer gọi selector dismiss.
@IBAction func showAlert(_ sender: Any) {
  let alert = UIAlertController(title: "WELCOME", message: "Tap outside to dismiss", preferredStyle: .alert)
  self.present(alert, animated: true) {
    alert.view.superview?.isUserInteractionEnabled = true
    alert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissOnTapOutside)))
  }
}

@objc func dismissOnTapOutside() {
  self.dismiss(animated: true, completion: nil)
}