【问题标题】:How to remove UIAlertAction from UIAlertController in Swift?如何在 Swift 中从 UIAlertController 中删除 UIAlertAction?
【发布时间】:2016-03-18 15:58:44
【问题描述】:

我知道您可以在 UIAlertController 中禁用 UIAlertAction 按钮,但是否可以在添加按钮后将其完全删除?

【问题讨论】:

    标签: ios uialertcontroller


    【解决方案1】:

    一旦添加,就无法从UIAlertController 中删除操作。

    actions 属性可以返回一个包含添加操作的数组,但它只是一个get,不能设置。

    使用addAction(_:) 方法添加操作,但没有对应的removeAction(_:) 方法。

    最终,一旦添加警报控制器,从警报控制器中删除操作并不一定很有意义。您通常应该在实例化后重用警报控制器对象,因此解决方案是首先仅添加适当的操作。

    【讨论】:

    • 添加后想要从警报控制器中删除操作非常有意义。它与重复使用无关。它与呈现简洁的界面有关。例如,如果您正在呈现一个警报控制器,该控制器用于为用户的头像选择一张照片,您可能希望为照片添加多个来源,并提供一个操作以完全删除当前照片如果它是已经设置了。当然,您可以禁用删除操作,但由于它并不总是一个选项,为什么要首先将其呈现给用户?
    • 我遇到的正是@cue8chalk 所描述的情况。每次我想删除“清除照片”操作时,都必须创建一个新的 UIAlertController 非常令人沮丧......
    【解决方案2】:

    由于您无法删除操作,因此有一种简单的“肮脏”方式。创建新警报:

    // Objective-C
    UIAlertController *replacingNewAlert = [UIAlertController alertControllerWithTitle:yourOldAlert.title message:yourOldAlert.message preferredStyle:yourOldAlert.preferredStyle];
    NSMutableArray* mutableActions = yourOldAlert.actions.mutableCopy;
    
    // remove any unwanted actions here ...
    
    for (UIAlertAction *action in mutableActions) {
        [replacingNewAlert addAction:action];
    }
    
    yourOldAlert = replacingNewAlert;
    

    当然,最好的方法是一开始就不要添加要删除的操作。

    【讨论】:

      【解决方案3】:

      您可以改用这种方式实现从UIAlertController 派生的自定义类并改用它。您基本上将操作设置推迟到UIAlertController,而是在派生类中捕获操作项,并在viewDidLoad 中将您保存的操作设置为操作UIAlertController 的操作。

      public class MutableUIAlertController : UIAlertController {
          var mutableActions:[UIAlertAction] = []
      
          override public func addAction(action: UIAlertAction) {
              mutableActions.append(action)
          }
      
          public func removeAction(action:UIAlertAction) {
              if let index = mutableActions.indexOf(action) {
                  mutableActions.removeAtIndex(index)
              }
          }
      
          override public func viewDidLoad() {
              for action in mutableActions {
                  super.addAction(action)
              }
              super.viewDidLoad()
          }
      }
      

      【讨论】:

      • 你不能继承 UIAlertController。 Apple Docs 说:重要 UIAlertController 类旨在按原样使用,不支持子类化。此类的视图层次结构是私有的,不得修改。
      猜你喜欢
      • 2016-01-01
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      相关资源
      最近更新 更多