[英]UIAlertController 'UIAlertAction' tag/userdata or anything in Swift
[英]How to remove UIAlertAction from UIAlertController in Swift?
我知道您可以在UIAlertController中禁用UIAlertAction按鈕,但是一旦添加按鈕就可以完全刪除它嗎?
添加后,無法從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
派生的自定義類,而是使用它。 您基本上將操作設置推遲到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()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.