这是我的代码: 请检查是否出了什么问题?请给我 UIActionsheet (UIAlertController) 的代码,其中包含 swift 中的数组
let alertA = UIAlertController(title: "PlayLists", message: "Select From PlayLists Below", preferredStyle: .ActionSheet)
let action = UIAlertAction(title: "Cancel", style: .Default, handler: {(alert: UIAlertAction!) in
})
let playListModel = PlayListModel.sharedInstance
plLists = playListModel.getPlayListNames()
for(var i = 0; i < plLists.count; i++){
alertA.addAction(UIAlertAction(title: plLists.objectAtIndex(i) as? String, style: .Default, handler: {
action in
NSLog("%@",String(i))
}))
}
alertA.addAction(action)
self.presentViewController(alertA, animated: true, completion: nil)
在此代码中,如果我有 3 个播放列表,则操作表会显示三个播放列表以及取消按钮。当我单击第一个按钮时,它将打印值 4(我停止递增的位置)。为什么要打印这个?它应该打印 i
值 1,对吧?有什么问题? For循环内的Action是否正确?
最佳答案
首先我要向你解释为什么会发生这种情况,你可以看到如果你触摸任何按钮总是调用NSLog("%@",String(i))
的输出结果。是plLists.count - 1
,这是因为您试图始终设置 for
的索引在您要添加的操作的闭包内声明。变量在闭包范围之外。
主要问题是,在您的案例中,保留在闭包内的引用始终是数组的最后一个索引,因为正如您所说,它增加了,最后在完成时分配了值。
不过,您可以采取一种方法来处理 title
action
中的属性(property),像下面这样:
func presentAction() {
let alertA = UIAlertController(title: "PlayLists", message: "Select From PlayLists Below", preferredStyle: .ActionSheet)
let action = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
let plLists = ["List1", "List2", "List3", "List4"]
for(var i = 0; i < plLists.count; i++) {
alertA.addAction(UIAlertAction(title: plLists[i], style: .Default, handler: self.handlerForAction))
}
alertA.addAction(action)
self.presentViewController(alertA, animated: true, completion: nil)
}
func handlerForAction(action: UIAlertAction) {
print(action.title!)
}
希望对你有帮助
关于ios - UIAlertController 给出错误?请在 Swift 中使用字符串数组作为按钮提供 UIAlertController 的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34068394/