1

如何处理点击警报控制器按钮的动作,然后继续关闭当前视图控制器?

一些代码和平:

 internal func dismissPasscodeLock(_ lock: PasscodeLockType, completionHandler: (() -> Void)? = nil) {
   
    // create the alert
       let alert = UIAlertController(title: "TouchID", message: "Message?", preferredStyle: UIAlertController.Style.alert)

       // add the actions (buttons)
    alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: {action in self.pressedAction()}))
       alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.cancel, handler: nil))
    
    let currentTopVC: UIViewController? = self.currentTopViewController()
    currentTopVC?.present(alert, animated: true, completion: nil)
    
    // if presented as modal
    if presentingViewController?.presentedViewController == self {
        dismiss(animated: animateOnDismiss) { [weak self] in
            
            self?.dismissCompletionCallback?()
            completionHandler?()
        }
    } else {
        // if pushed in a navigation controller
        _ = navigationController?.popViewController(animated: animateOnDismiss)
        dismissCompletionCallback?()
        completionHandler?()
    }
}

func pressedAction(){}

func currentTopViewController() -> UIViewController {
    var topVC: UIViewController? = UIApplication.shared.delegate?.window??.rootViewController
    while ((topVC?.presentedViewController) != nil) {
        topVC = topVC?.presentedViewController
    }
    return topVC!
}

提前致谢

4

1 回答 1

1

您可以使用这样的完成处理程序创建一个函数来获取警报的输出

    func showAlert(completion: @escaping () -> Void) {
     let alert = UIAlertController(title: "TouchID", message: "Message?", preferredStyle: UIAlertController.Style.alert)
    
           // add the actions (buttons)
        alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: {action in 
              self.pressedAction()
              completion()
            }))
       alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.cancel, handler: {
             completion()
           }))
        
        let currentTopVC: UIViewController? = self.currentTopViewController()
        currentTopVC?.present(alert, animated: true, completion: nil)
    }

如何使用

internal func dismissPasscodeLock(_ lock: PasscodeLockType, completionHandler:@escaping (() -> Void)? = nil) {
   
    // create the alert
       showAlert {
            
        
    // if presented as modal
    if presentingViewController?.presentedViewController == self {
        dismiss(animated: animateOnDismiss) { [weak self] in
            
            self?.dismissCompletionCallback?()
            completionHandler?()
        }
    } else {
        // if pushed in a navigation controller
        _ = navigationController?.popViewController(animated: animateOnDismiss)
        dismissCompletionCallback?()
        completionHandler?()
    }
  }
}
于 2020-07-03T14:14:52.943 回答