如果已经添加了 UIAlertAction,如何不将其添加到 UIActionSheet

How to not add UIAlertAction to UIActionSheet if it has already been added

我正在使用以下代码添加 UIAlertAction:

    @IBAction func doneButtonTapped(_ sender: Any) {
        
        self.present(lastInstructionAlert, animated: true, completion: nil)
        
        lastInstructionAlert.addAction(UIAlertAction(title: "Back", style: .default, handler: { (action) in
            print("Go Back")
            return
        }))
        
        lastInstructionAlert.addAction(UIAlertAction(title: "Home", style: .default, handler: { (action) in
            print("Go Home")
            self.present(self.mealPlanViewController, animated: true, completion: nil)
        }))
        
    }

问题是,当用户再次按下“返回”然后“完成”时,它会再次添加 UIAlertAction,从而导致重复。

如果之前已经添加了这些 UIAlertActions,我该如何防止再次添加它们?

当您每次单击操作时都将 lastInstructionAlert 设为实例变量 doneButtonTapped 添加了新的警报操作,因此将其设为本地

@IBAction func doneButtonTapped(_ sender: Any) {
    
   let lastInstructionAlert = UIAlertController(title: "Well done,chef!", message: "It's time to eat", preferredStyle: .alert)

    lastInstructionAlert.addAction(UIAlertAction(title: "Back", style: .default, handler: { (action) in
        print("Go Back")
        return
    }))
    
    lastInstructionAlert.addAction(UIAlertAction(title: "Home", style: .default, handler: { (action) in
        print("Go Home")
        self.present(self.mealPlanViewController, animated: true, completion: nil)
    }))
     
    self.present(lastInstructionAlert, animated: true, completion: nil)
}

或将警报操作添加到 viewDidLoad

问题出在action的编码上sheet,请按照我下面做的功能在你的项目中使用,如果你愿意,可以添加更多的按钮。

我会推荐创建一个新项目,并将这个函数(按原样)放在视图控制中并在 viewDidload 中调用它以查看它是如何工作的。然后您可以 adjust/alter 主项目的代码。

/**
 Simple Action Sheet
 - Show action sheet with title and alert message and actions
 */
func showSimpleActionSheet(controller: UIViewController) {
    let alert = UIAlertController(title: "Title", message: "Please Select an Option", preferredStyle: .actionSheet)
    alert.addAction(UIAlertAction(title: "Approve", style: .default, handler: { (_) in
        print("User click Approve button")
    }))

    alert.addAction(UIAlertAction(title: "Edit", style: .default, handler: { (_) in
        print("User click Edit button")
    }))

    alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { (_) in
        print("User click Delete button")
    }))

    alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: { (_) in
        print("User click Dismiss button")
    }))

    self.present(alert, animated: true, completion: {
        print("completion block")
    })
}

这是我项目中 swift 的旧版本。如果您将它粘贴到您的项目中,xcode 将在弹出警告时自动修复它。您只需点击它们,它就会被修复。