在iOS中,如何通过点击警告弹出窗口中的关闭警报控制器?

时间:2018-01-20 03:10:00

标签: ios swift swift4 uialertcontroller uicontrol

通过点击 OUTSIDE 弹出窗口,有几篇关于如何解除警报控制器弹出窗口的帖子。但我想通过点击 INSIDE 弹出窗口来关闭警报控制器弹出窗口。

我见过一些" Toast"喜欢GitHub上的解决方案,但我想用原生iOS代码来做这件事。

我已经在SO周围徘徊,并在几秒钟之后获得了解除警报的代码(如Android Toast):

class ViewController: UIViewController {
    let alertController = UIAlertController(title: "Alert", message: "SO Awesome!", preferredStyle: .alert)

    @IBOutlet var alertButton: UIButton!

    @IBAction func displayAlert(_ sender: UIButton) {
        self.present(alertController, animated: true, completion: {
            self.perform(#selector(self.dismissAlert), with: self.alertController, afterDelay: 3)
        })
    }

    // dismiss (close) the alert popup
    @objc func dismissAlert(_ alert: UIAlertController) {
        alert.dismiss(animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

但是,如果我不想等待3秒钟让弹出警报关闭怎么办?我希望能够点击弹出警报来关闭它。 (并且还保留超时功能)

我发现了一些很接近但不完全符合我要求的东西。所以......经过一些工作,我自己回答了这个问题,并在下面提供了完整的答案。

1 个答案:

答案 0 :(得分:1)

我在SO上找到的最简单的技巧似乎是添加一个带有动作目标的UIControl,它可以解决任何触摸事件中的AlertController。但是UIControl需要一个框架CGRect才能正常运行。

以下是UIControl的重点:

let dismissControl = UIControl()

// make the dismissControl execute dismissAlert for all touch events
dismissControl.addTarget(self, action: #selector(self.dismissAlert), for: .allTouchEvents)

// NOTE:  must use the bounds, not the frame for it to work
self.dismissControl.frame = self.alertController.view.bounds

// add the UIControl on top of the UIAlertControl view
self.alertController.view.addSubview(self.dismissControl)

我探索了4种不同的可能性:

  • 超时 - 在几秒钟后关闭警报窗口(如Android Toast)
  • 在提醒窗口外点击(点击提醒窗口不要关闭它)
  • 点按屏幕上的任意位置以关闭它(在提醒窗口或其外部)
  • 点按提醒窗口(点击其他任何地方都不要关闭它)

这是一个完整的ViewController (Xcode 9.2,Swift 4),它可以处理所有4种情况:

//
//  ViewController.swift
//  AlertDemo - Display and dismiss UIAlertControllers with UIControl (no action buttons)
//              (similar to Toast on Android OS)
//
//      4 different ways to close a UIAlertController popup window:
//
//      1) Timeout - dismiss an Alert Window after a number of seconds (like Android Toast)
//      2) Tap outside the Alert Window (tap on Alert Window DOES NOT close it)
//      3) Tap the Alert Window (tap anywhere else DOES NOT close it)
//      4) Tap anywhere on the screen (on Alert Window or outside of it) to close it

//
//  Created by ByteSlinger on 2018-01-19.
//  Copyright © 2018 ByteSlinger. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    let alertController = UIAlertController(title: "Alert", message: "SO Awesome!", preferredStyle: .alert)
    let timeoutController = UIAlertController(title: "Timeout", message: "That Alert timed out!", preferredStyle: .actionSheet)
    let dismissControl = UIControl()

    @IBOutlet var alertButton1: UIButton!
    @IBOutlet var alertButton2: UIButton!
    @IBOutlet var alertButton3: UIButton!
    @IBOutlet var alertButton4: UIButton!

    // display a modal popup in the middle, wait for timeout to close
    @IBAction func displayAlert1(_ sender: UIButton) {
        alertController.message = "You must wait for this Alert to timeout"

        self.present(alertController, animated: true, completion: {
            self.perform(#selector(self.timeoutAlert), with: self.alertController, afterDelay: 3)
        })
    }

    // display a modal popup in the middle, tap outside popup to close
    @IBAction func displayAlert2(_ sender: UIButton) {
        alertController.message = "Tap outside this Alert to close"

        self.present(alertController, animated: true, completion: {
            self.dismissControl.frame = self.alertController.view.superview?.bounds ?? CGRect.zero

            self.alertController.view.superview?.insertSubview(self.dismissControl, belowSubview: self.alertController.view)

            self.perform(#selector(self.timeoutAlert), with: self.alertController, afterDelay: 3)
        })
    }

    // display a modal popup in the middle, tap on or outside popup to close
    @IBAction func displayAlert3(_ sender: UIButton) {
        alertController.message = "Tap anywhere to close"

        self.present(alertController, animated: true, completion: {
            self.dismissControl.frame = self.alertController.view.superview?.bounds ?? CGRect.zero

            self.alertController.view.superview?.addSubview(self.dismissControl)

            self.perform(#selector(self.timeoutAlert), with: self.alertController, afterDelay: 3)
        })
    }

    // display a modal popup in the middle, tap on popup to close
    @IBAction func displayAlert4(_ sender: UIButton) {
        alertController.message = "Tap on this Alert to close"

        self.present(alertController, animated: true, completion: {
            // important - use bounds:  alertController.view.frame WILL NOT WORK
            self.dismissControl.frame = self.alertController.view.bounds

            self.alertController.view.addSubview(self.dismissControl)

            self.perform(#selector(self.timeoutAlert), with: self.alertController, afterDelay: 3)
        })
    }

    // close the current alert popup (middle) and display the timeout alert (bottom)
    @objc func timeoutAlert(_ alertController: UIAlertController) {
        if (alertController == UIApplication.shared.keyWindow?.rootViewController?.presentedViewController) {
            timeoutController.message = alertController.message!

            alertController.view.willRemoveSubview(self.dismissControl)

            alertController.dismiss(animated: true, completion: {
                self.present(self.timeoutController,animated: true, completion: {
                    self.perform(#selector(self.dismissTimeout), with: self.timeoutController, afterDelay: 2)
                })
            })
        }
    }

    // dimiss (close) the alert popup
    @objc func dismissAlert() {
        // make sure there are no timeoutAlert calls waiting
        NSObject.cancelPreviousPerformRequests(withTarget: self)

        alertController.view.willRemoveSubview(self.dismissControl)

        alertController.dismiss(animated: true, completion: nil)
    }

    // dimiss (close) the timeout popup
    @objc func dismissTimeout(_ alert: UIAlertController) {
        alert.dismiss(animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // make the dismissControl execute dismissAlert for all touch events
        dismissControl.addTarget(self, action: #selector(self.dismissAlert), for: .allTouchEvents)

        // make the buttons a little prettier
        alertButton1.layer.cornerRadius = 32
        alertButton2.layer.cornerRadius = 32
        alertButton3.layer.cornerRadius = 32
        alertButton4.layer.cornerRadius = 32
    }
}

要使用它,只需在IB中创建4个UIButtons并将它们连接到@IBOutlet变量和函数。

注意:我必须取消执行请求,或者有时警报会被先前的超时取消。 dismissAlert()中的这一行做了诀窍:

NSObject.cancelPreviousPerformRequests(withTarget: self)

以下是GitHub上的完整Xcode项目:AlertDemo

感谢 @Apoc 以及此帖中UIControl的灵感:UIAlertController handle dismiss upon click outside (IPad)。从UIAlertController边界设置UIControl帧是最终使它工作的原因。