首页 > 解决方案 > 如何在我的视图控制器中向我的“全部删除”和“保存”按钮添加警报?

问题描述

我以编程方式在我的 viewController 中添加了按钮,我想在点击将出现警报的按钮时添加一个警报并删除我的 TableViewCell 中所有添加的项目。我怎样才能做到这一点?以及点击按钮时的保存按钮,将出现保存按钮的警报。谢谢你。

class IncallPantryCheckViewController {

let deleteAllButton: UIButton = {
        let button = UIButton()
        button.setTitle("Delete All", for: .normal)
        button.titleLabel!.font = UIFont(name: "HelveticaNeue-Bold", size: 20.0)!
        button.setTitleColor(UIColor.orange, for: UIControlState.normal)
        return button
    }()
  

 override func viewDidLoad() {
        super.viewDidLoad()
        
        inCallTableView.register(UINib(nibName: "PantryCheckInCallTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: "PantryCheckInCallTableViewCell")
        
view.addSubview(deleteAllButton)
view.addSubview(saveButton)

deleteAllButton.translatesAutoresizingMaskIntoConstraints = false
deleteAllButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true
deleteAllButton.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 45).isActive = true
        
saveButton.translatesAutoresizingMaskIntoConstraints = false
saveButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20).isActive = true
saveButton.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -45).isActive = true
    



 }
}

标签: swiftuitableviewswift3

解决方案


我假设您要使用 iOS 提供的警报:

  1. 创建函数以显示删除警报并实际执行删除:

     @objc func tappedDelete() {
         let alertController = UIAlertController(title: "Alert", message: "Are you sure you want to delete?", preferredStyle: .alert)
         alertController.addAction(UIAlertAction(title: "YES", style: .destructive, handler: { _ in
             self.performDelete()
         }))
         alertController.addAction(UIAlertAction(title: "NO", style: .cancel, handler: nil))
    
         // present alert, pick one depending if you're using a navigation controller or not.
         //    self.navigationController?.present(alertController, animated: true, completion: nil)
         //    self.present(alertController, animated: true, completion: nil)
     }
    
     func performDelete() {
         print("Do your delete logic here")
     }
    
  2. 将目标操作添加到您的按钮:

     deleteAllButton.addTarget(self, action: #selector(tappedDelete), for: .touchUpInside)
    

对您的保存按钮重复上述操作。


推荐阅读