2015-08-23 25 views
0

我的單元格中顯示圖像視圖,其中顯示覆選標記圖標。swift table view將自定義複選標記添加到單元格並刪除前一個單元格的複選標記

我想要做的是當你觸摸一個單元格時,應該出現複選標記。我得到了這個工作,但我現在的問題是,我不能刪除前一個選定單元格的複選標記。 - 只能選擇一個單元格。

我試圖讓這個工作在didSelectRowAtIndexPath但我不能正確的,所以我現在卡住了。

更新:

var selectedRow: NSIndexPath? 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     var cell: searchCityTableViewCell! 

     if (indexPath.section == 0) { 
      cell = tableView.dequeueReusableCellWithIdentifier("staticCityCell") as! searchCityTableViewCell 
      cell.titleLabel?.text = "Within \(stateName)"     
     }else if (indexPath.section == 1) { 
      cell = tableView.dequeueReusableCellWithIdentifier("cityCell") as! searchCityTableViewCell 
      let state = cities[indexPath.row] 
      cell.configureWithStates(state) 
      if indexPath == selectedRow { 
       cell.cityImage.select() 
      } else { 
       cell.cityImage.deselect() 
      } 
     } 

     return cell 

    } 

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 
    { 
     let paths:[NSIndexPath] 

     if let previous = selectedRow { 
      paths = [indexPath, previous] 
     } else { 
      paths = [indexPath] 
     } 
     selectedRow = indexPath 
     tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: .None) 
    } 
+0

http://stackoverflow.com/a/7172609/4475605 – Adrian

回答

4
  1. 跟蹤哪些當前被選中的行。一個屬性添加到您的ViewController:

    var selectedRow: NSIndexPath? 
    
  2. didSelectRowAtIndexPath

    let paths:[NSIndexPath] 
    
    if let previous = selectedRow { 
        paths = [indexPath, previous] 
    } else { 
        paths = [indexPath] 
    } 
    selectedRow = indexPath 
    tableView.reloadRowsAtIndexPaths(paths, withRowAnimation: .None) 
    
  3. cellForRowAtIndexPath

    if indexPath == selectedRow { 
        // set checkmark image 
    } else { 
        // set no image 
    } 
    

要注意的重要一點是,其狀態選擇的行應存儲在模型中而不存儲在單元格中。該表應該反映模型的狀態。在這種情況下,該模型可以簡單地爲所選行的indexPath。一旦模型更新(設置了selectedRow),受影響的行應重新加載其狀態。

+0

我在'cellForRowAtIndexPath'中看到一個錯誤 如果我選擇列表中的第一個項目,然後向下滾動,使項目不顯示在我的屏幕上,一旦我在屏幕上再次顯示時再次向上滾動,該項目將被重新選擇 –

+0

這不是一個錯誤。這正是它應該如何工作。你爲什麼想要這行被取消選擇,只是因爲它脫離屏幕並返回? – vacawama

+0

那就是我的意思,我(不)不希望它被取消,只是因爲它脫離了屏幕。任何想法是什麼造成的? –

相關問題