ios - UIAlertController 给出错误?请在 Swift 中使用字符串数组作为按钮提供 UIAlertController 的代码

标签 ios swift uialertcontroller

这是我的代码: 请检查是否出了什么问题?请给我 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/

相关文章:

ios - 节点上的 Sprite Kit 相机

ios - 使用 Model 中的 Alert 类访问 UIAlert TextField 中的文本

ios - 检查 UIAlertController 是否出现在 XCTest 案例中

ios - 3.2 带有占位符文本的应用程序将被拒绝

ios - 如何区分单击手势和双击手势?

ios - 指定的捆绑 iOS 应用程序中不存在许可文件

ios - 在 coreplot ios 的同一 Y 轴上绘制负值和正值

ios - SwiftUI:自定义按钮无法识别具有清晰背景和 buttonStyle 的触摸

xcode - 无法从 XCode Playground 中导入的框架访问类

ios - UIAlertController 操作表中的 UIPickerView 未显示任何数据