【发布时间】:2016-03-18 15:58:44
【问题描述】:
我知道您可以在 UIAlertController 中禁用 UIAlertAction 按钮,但是否可以在添加按钮后将其完全删除?
【问题讨论】:
标签: ios uialertcontroller
我知道您可以在 UIAlertController 中禁用 UIAlertAction 按钮,但是否可以在添加按钮后将其完全删除?
【问题讨论】:
标签: ios uialertcontroller
一旦添加,就无法从UIAlertController 中删除操作。
actions 属性可以返回一个包含添加操作的数组,但它只是一个get,不能设置。
使用addAction(_:) 方法添加操作,但没有对应的removeAction(_:) 方法。
最终,一旦添加警报控制器,从警报控制器中删除操作并不一定很有意义。您通常应该在实例化后重用警报控制器对象,因此解决方案是首先仅添加适当的操作。
【讨论】:
由于您无法删除操作,因此有一种简单的“肮脏”方式。创建新警报:
// 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;
当然,最好的方法是一开始就不要添加要删除的操作。
【讨论】:
您可以改用这种方式实现从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()
}
}
【讨论】: