从indexPathsForSelectedRows()中提取数据 - SWIFT

问题描述:

我试图从表中选定的行提取所有数据。我使用下面的代码来打印indexPaths。但是,我需要做些什么才能打印出选定行中的文本?从indexPathsForSelectedRows()中提取数据 - SWIFT

 let indexPaths:NSArray = tableView.indexPathsForSelectedRows()! 


      `for var i = 0; i < indexPaths.count; ++i { 

      var thisPath:NSIndexPath = indexPaths.objectAtIndex(i) as NSIndexPath 

      println("row = \(thisPath.row) and section = \(thisPath.section)") 
     } 

打印到控制台所选行

row = 1 and section = 0 
row = 3 and section = 0 

row = 6 and section = 0

+1

从数据模型中获取数据的方式与您在cellForRowAtIndexPath中获取的数据完全相同? – nhgrif 2014-11-23 13:25:38

可以使用的UITableViewcellForRowAtIndexPath方法通过索引路径以获得细胞:

if let indexPaths = tableView.indexPathsForSelectedRows() { 
    for var i = 0; i < indexPaths.count; ++i { 

     var thisPath = indexPaths[i] as NSIndexPath 
     var cell = tableView.cellForRowAtIndexPath(thisPath) 
     if let cell = cell { 
      // Do something with the cell 
      // If it's a custom cell, downcast to the proper type 
     } 
    } 
} 

注意indexPathsForSelectedRows返回一个可选项(无没有行被选中),所以最好用可选的绑定来保护它以防止运行时异常。

+0

安东尼奥,当我使用你的代码时,我得到一个错误声明“var thisPath”。在那一行我得到一个'[AnyObject]'没有名为'objectAtIndex'的成员。 – Tom 2014-11-23 20:04:46

+0

我的错误 - 代码固定,用下标代替'objectAtIndex'。如果你仍然得到'thisPath'的错误,这意味着你有一个在方法(或类属性)中具有相同名称的变量 - 只需将其重命名为其他内容即可,例如'currentPath' – Antonio 2014-11-23 20:14:28

+0

使用'var thisPath =(indexPaths!作为[NSIndexPath])[i]' – 2014-11-23 20:14:32