解雇 UIAlertController(最佳实践)

Posted

技术标签:

【中文标题】解雇 UIAlertController(最佳实践)【英文标题】:Dismissal of UIAlertController (best practice) 【发布时间】:2014-08-17 12:56:35 【问题描述】:

当像这样使用 UIAlertController 时:

var alert = UIAlertController(title: "Core Location", 
     message: "Location Services Disabled!", 
     preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, 
     handler: nil))
self.navigationController.presentViewController(alert, animated: true, 
     completion: nil)

我注意到警报视图的关闭似乎是自动完成的。 不应该由呈现 ViewController 通过委托调用来解除呈现的 ViewController 吗?

【问题讨论】:

【参考方案1】:

解雇被“包含”在presentViewController 调用中。您不需要委托,因为您有完成块。在此块中,您将通常放入委托回调中的内容放入委托回调中,但解除警报的调用除外。

就“最佳实践”而言,我注意到在许多 API 中,Apple 将委托回调替换为完成块。 Apple 通常建议使用块语法。我猜这可能部分是因为它有助于将相关的代码部分保持在一起。

【讨论】:

谢谢 - 所以我们不再需要代理来解除模态视图控制器了? - 解雇电话包括在哪里? 它不必明确地完成。当您按下警报上的按钮时,它会自动关闭。 这个答案可以被解读为暗示当警报被解除时,presentViewController:animated:completion 方法的 completion 闭包被调用。如果您以这种方式阅读,请注意事实并非如此。正如docs 所说:“在 viewDidAppear 之后调用完成处理程序:在呈现的视图控制器上调用方法”。即与解雇无关 不,此方法的completion 参数用于在呈现视图控制器的动画完成后的“回调”。这是有道理的——非模态视图控制器可以无限期地保持。我同意这可能会造成混淆,但请注意该参数不是“完成”而是“处理程序”,表明存在这一重要区别。 ios 9(也可能是 iOS 8)中,completion 块到 -presentViewController:animated:completion: 是在 UIAlertController 首次出现之后执行的。如果您需要在用户关闭警报控制器时进行回调,则提供类型为 UIAlertActionStyleCancel 的 UIAlertAction,并将您的代码放入该对象的 handler。当通过点击弹出框外部或点击取消按钮关闭警报控制器时,它将执行。【参考方案2】:

有一种优雅的方式!只需在警报控制器的取消操作中编写操作或函数。 (这里的动作风格应该是.cancel

Swift 3 代码:

let Alert: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)

    let OkAction: UIAlertAction = UIAlertAction(title: “Ok”, style: .default)  ACTION in

       //Will be called when tapping Ok

    

    let CancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) ACTION in

      // Will be called when cancel tapped or when alert dismissed.
      // Write your action/function here if you want to do something after alert got dismissed”

    

    Alert.addAction(OkAction)
    Alert.addAction(CancelAction)

present(Alert, animated: true, completion: nil)

【讨论】:

如果您想在解雇时执行某些操作,则必须将其添加到每个操作中,因为例如,点击确定也会取消警报。【参考方案3】:

你可能喜欢用这个吗:

  class MyAlertController : UIAlertController 
    var dismissHandler : (()->())?
    override func viewDidDisappear(_ animated: Bool) 
      dismissHandler?()
      super.viewDidDisappear(animated)
    
  

用法:

  let alert = MyAlertController(title: ...
  let cancelButton = UIAlertAction(titl
  alert.dismissHandler =  /*...do something */ 
  alert.addAction(cancelButton)
  ...

【讨论】:

以上是关于解雇 UIAlertController(最佳实践)的主要内容,如果未能解决你的问题,请参考以下文章

带有呈现的 UIAlertController 的 UINavigationController 被另外解雇

不要关闭 UIAlertController

UIAlertController 的文本字段委托没有被调用

模仿 UIAlertController 显示动画

检查UIAlertController是否已经呈现的最佳方法是什么?

Helm(三)—最佳实践