2017-04-21 33 views
0

我已閱讀this link並且解決方案對我無效。UITableviewCell只觸發一個自定義複選標記狀態不起作用 - Swift 3

我想選擇一行,當我選擇它時,它會向標籤添加複選標記。如果在存在複選標記的情況下選擇了另一行,它將取消選中存儲在selectedIndexPath變量中的前一行。

但是通過實現代碼如下幾次滾動時它的工作原理在開始的時候,我偶爾看到選定的單元格不應該在該圖像中所示:

enter image description here

我所當做用戶選擇的小區:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 

    if let cell = tableView.cellForRow(at: indexPath) as? CustomCell { 
     let customCell = customCellData[indexPath.row] 
     customCell.toggleSelected() 
     cell.configureCheckmark(with: customCell) 
    } 

    if let oldIndexPath = selectedIndexPath, let cell = tableView.cellForRow(at: oldIndexPath) as? CustomCell, oldIndexPath.row != indexPath.row { 
     let customCell = customCellData[oldIndexPath.row] 
     customCell.toggleSelected() 
     cell.configureCheckmark(with: customCell) 
    } 


    if let selected = selectedIndexPath, selected.row == indexPath.row { 
     selectedIndexPath = nil 
     tableView.deselectRow(at: indexPath, animated: true) 
    } else { 
     selectedIndexPath = indexPath 
    } 

} 

和在cellForRowAt:(是它的冗餘檢查selectedIndexPath和在模型中的狀態?)

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell 
    let customCell = customCellData[indexPath.row] 
    cell.customCell = customCell 
    if selectedIndexPath == indexPath { 
     cell.checkLabel.text = "✔️" 
    } else { 
     cell.checkLabel.text = "" 
    } 

    return cell 
} 

終於在CustomCell:

var customCell: CustomCell? { 
    didSet { 
     if let customCell = customCell { 
      configureCheckmark(with: customCell) 
     } 
    } 
} 

func configureCheckmark(with customCell: CustomCellData) { 
    if customCell.isSelected { 
     checkLabel.text = "✔️" 
    } else { 
     checkLabel.text = "" 
    } 
} 

CustomCellData我切換狀態如下:

class CustomCellData { 
    var isSelected = false 

    func toggleSelected() { 
     isSelected = !isSelected 
    } 
} 

我摸不着這個我的頭,不清楚該怎麼做,任何幫助會很好。

回答

1

最簡單的辦法是減少didSelectRowAt

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
{ 
    selectedIndexPath = indexPath 
    tableView.reloadData() 
} 

這正常更新所有可見的單元格。

或者更先進的版本,如果小區已經選擇

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
{ 
    if selectedIndexPath != indexPath { 
     let indexPathsToReload = selectedIndexPath == nil ? [indexPath] : [selectedIndexPath!, indexPath] 
     selectedIndexPath = indexPath 
     tableView.reloadRows(at: indexPathsToReload, with: .none) 
    } else { 
     selectedIndexPath = nil 
     tableView.reloadRows(at: [indexPath], with: .none) 
    } 
} 

cellForRowAt的代碼沒有休息這僅更新受影響的行和檢查。

+0

這有效,但如果我想取消選中相同的單元格,我該如何去做呢?如果它們相同,我會將'selectedIndexPath'設置爲'nil'嗎? – Simon

+0

我更新了答案。順便說一句:處理「CustomCellData」中的複選標記的自定義代碼也不需要。 – vadian

相關問題