2015-02-10 93 views
0

我有一個NSMutableArray(array2)作爲表視圖的數據源。當我選擇一個searchResultsTableView單元格並重新加載self.tableView與該數組時,我想添加對象到該數組。表格單元格顯示swift中NSMutableArray的第一個索引的數據

如果我用array2.addObject()方法添加對象,那麼所有的單元格都可以使用單個數據。但是,如果我用array2.insertObject(myObject,atIndex:0)添加對象,則所有單元顯示與array2 [0]的數據相同的數據。爲什麼?

我的問題是在表視圖的didSelectRowAtIndexPath函數。我總是想在我的表視圖的第一個位置添加選定的對象,這就是爲什麼我使用insertObject方法而不是addObject方法實現的。以下是我的代碼部分。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     if tableView == self.searchDisplayController!.searchResultsTableView { 
      return self.array1.count 
     }else{ 
      return self.array2.count 
     } 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = UITableViewCell() 
     if tableView == self.searchDisplayController!.searchResultsTableView { 
      let number = self.array1[indexPath.row] 
      cell.textLabel?.text = String(number) 
     } else { 
      let cell: customCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as customCell 
      let brand = self.array2[indexPath.row] as NSString 
      cell.name.text = brand 
      cell.comment.text = "100" 
     } 

     return cell 
    } 

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
     if tableView == self.searchDisplayController!.searchResultsTableView { 
      let cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell! 

      self.array2.insertObject(cell.textLabel!.text!, atIndex: 0) 
      //self.array2.addObject(cell.textLabel!.text!) 

      self.searchDisplayController!.setActive(false, animated: true) 
      self.tableView.reloadData() 
     } 
    } 

回答

2

你的cellForRowAtIndexPath方法是怪異......你總是返回「讓電池= UITableViewCell的()」,而不是實際上你取出的「細胞」

改變你的方法是:!

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    if tableView == self.searchDisplayController!.searchResultsTableView { 
     let number = self.array1[indexPath.row] 
     let cell = UITableViewCell() 
     cell.textLabel?.text = String(number) 
     return cell 
    } else { 
     let cell: customCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as customCell 
     let brand = self.array2[indexPath.row] as NSString 
     cell.name.text = brand 
     cell.comment.text = "100" 
     return cell 
    } 
} 
+0

謝謝,它的工作。 – Nuibb 2015-02-10 12:10:57

相關問題