问题描述
我已通过编程方式在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
}
}
解决方法
我假设您要使用iOS提供的警报:
-
创建功能以显示删除警报并实际执行删除操作:
@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,completion: nil) } func performDelete() { print("Do your delete logic here") }
-
将目标操作添加到您的按钮:
deleteAllButton.addTarget(self,action: #selector(tappedDelete),for: .touchUpInside)
在上方重复您的保存按钮。