swift - 如何在我的视图控制器中向我的“全部删除”和“保存”按钮添加警报?
问题描述
我以编程方式在我的 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, animated: true, completion: nil) } func performDelete() { print("Do your delete logic here") }
将目标操作添加到您的按钮:
deleteAllButton.addTarget(self, action: #selector(tappedDelete), for: .touchUpInside)
对您的保存按钮重复上述操作。
推荐阅读
- go - Go:如何解决作为参数在两个包之间传递的结构的依赖关系?
- docker - docker image - 中间容器问题
- firebase - 获取 Firestore 用户数据以更新视图时略有延迟/滞后
- docker - 如何解决 MySQL 数据库数据在 Docker Swarm 中消失的问题
- reactjs - 错误:对象作为 React 子项无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组(React)
- python - 为什么没有解释和(真正)编译的语言?
- github - 我的 AWS CDK 管道中缺少 UpdatePipeline (SelfMutate) 阶段
- c# - 如何在 Blazor 服务器端使用模拟访问文件服务器上的文件夹
- javascript - 如何获取迭代 HTML 集合的特定 DOM 元素的路径?
- vue.js - vue,veeValidator,以编程方式验证字段