我有一个包含5个单元格的表视图,每个单元格都有自己的标识符,我试图从每个UITextFields获取print字符串,还有一些标签。这是我的代码:

 let index: NSIndexPath = NSIndexPath(forRow:0 ,  inSection: 0)
            let cell: CustomCell = tableView.cellForRowAtIndexPath(index) as! CustomCell
            print(cell.title.text!)

它可以正常工作,直到我动态地设置行值,例如,如果选择了单元格0中的textfield,则打印cell.title.text如果textfield字符串来自单元格1,则打印其值。所以我加上这行代码:
   let IndexPath:NSIndexPath = tableView.indexPathForSelectedRow!
        switch IndexPath.row {
        case 0:
            row = 0

        case 1:
            row = 1

        default:
            break
        }


            let index: NSIndexPath = NSIndexPath(forRow:row /***CHANGED VALUE***/ ,  inSection: 0)
            let cell: CustomCell = tableView.cellForRowAtIndexPath(index) as! CustomCell
            print(cell.title.text!)

应用程序在此行崩溃:
let IndexPath:NSIndexPath = tableView.indexPathForSelectedRow!

由于fatal error: unexpectedly found nil while unwrapping an Optional value。任何帮助都很好!

最佳答案

indexPathForSelectedRow可以在未选择任何行时返回nil。所以你必须检查它是否存在于任何卸载操作之前。

if let IndexPath:NSIndexPath = tableView.indexPathForSelectedRow {
    //do your work
}

关于ios - 从自定义UITableViewCell中的某些文本字段获取字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38421711/

10-12 01:23
查看更多