2014-11-23 63 views
0

我試圖從表中選定的行提取所有數據。我使用下面的代碼來打印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

回答

3

可以使用的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