2016-02-04 24 views
0

我想獲取tableview中的所有選定值。獲取所有tableview單元格與附件類型複選標記

例如:

// I'm unable to loop through the tableview (myTableView.cells is not valid) 
func saveClicked(sender:AnyObject) 
{ 
let testArray = NSMutableArray() 

    for i in myTableView.cells 
    { 
    if (i.accessorytype = .CheckMark) 
    { 
     testArray.addObject(i) 
    } 
    } 
} 
+6

從您的數據源獲取值,而不是視圖負責提供數據。 –

+0

您將需要從上述數據源獲取此信息。如果嘗試迭代tableView中的所有單元格,則只會收到當時可見行的數據,因爲不可見行將從內存中出列並重用單元。 – MikeG

+0

所以,無論你填充你的tableView,你都需要跟蹤該數組的'.Checkmark'狀態。然後,您只需遍歷數組中的具有'.Checkmark'狀態的值 – MikeG

回答

0

下面是一個簡化的例子。設置你的一系列物品,myItemsArray,並給它一個isChecked財產,這是一個bool。然後在didSelectRow方法中,相應地將isChecked值切換爲truefalse。然後,當您想要查找哪個「單元格」時,技術上myItemsArray中的項目的值爲true,您可以按如下所示遍歷數組。請讓我知道,如果這不清楚。

var myItemsArray = [Items]() 
var checkedItemsArray = [Items]() 

override func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ 
    if cell.accessoryType == .Checkmark { 
     cell.accesoryType == .None 
     myItemsArray[indexPath.row].isChecked == false 
    } else if cell.accessoryType == .None { 
     cell.accesoryType = .Checkmark 
     myItemsArray[indexPath.row].isChecked == true 
    } 
} 

    func saveClicked(){ 
    myItemsArray.removeAll() 

    for i in 0...myItemsArray.count-1 { 
     if myItemsArray[i].isChecked == true{ 
      checkedItemsArray.append(myItemsArray[i]) 
     } 
    } 
} 
+0

我不確定您的'saveClicked'函數是否正確; 'for'語句中的'i'應該只是數組中的對象,所以代碼可以簡化爲:'for i in myItemsArray {i = i.isChecked == true { checkedItemsArray.append(i) } }'。你也應該在函數的開頭清除'checkedItemsArray'。 –

+0

另外,在你的'tableView :: didSelectRowAtIndexPath:'方法中,你在哪裏定義或檢索'cell'對象? –

+0

我只是修復了'for-loop'感謝您的支持!在myItemsArray.count-1之前忘了'0 ...'。清除陣列也很好。這是我不幸遇到的第一個bug。正如我所說,這是一個簡單的例子。問題提問者可以從例子中推斷出他們需要用'let cell = tableView.cellForRowAtIndexPath(indexPath)'來定義'cell' – MikeG

1
  1. 你想要的實現代碼如下細胞默認勾選,然後單擊添加

cell.accessoryType = .Checkmark

在 「的cellForRowAtIndexPath」 委託方法

  • 如果您想選中行,請選中
  • 倍率FUNC的tableView(的tableView:UITableView的,didSelectRowAtIndexPath方法indexPath:NSIndexPath){ 如果cell.accessoryType == .Checkmark { cell.accesoryType == .None }否則如果cell.accessoryType == .None { 細胞.accesoryType = .Checkmark } }

    相關問題