私はthis linkを見直しました。UITableviewCellはカスタムチェックマーク状態を1つだけトグルします - スウィフト3
1つの行を選択しようとしていますが、選択するとラベルにチェックマークが追加されます。既存のチェックマークがある間に別の行が選択された場合は、selectedIndexPath
変数に格納されている前のチェックマークのチェックを外します。私がやっている何
:
テーブルビューを通じて数回スクロールしたときにそれはしかし、初めに働く、私は時折、この画像で示されるべきではない選択したセルを参照してくださいユーザがセルを選択:
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
}
し、最終的に:CustomCellData
で
var customCell: CustomCell? {
didSet {
if let customCell = customCell {
configureCheckmark(with: customCell)
}
}
}
func configureCheckmark(with customCell: CustomCellData) {
if customCell.isSelected {
checkLabel.text = "✔️"
} else {
checkLabel.text = ""
}
}
次のように私は状態を切り替え:
class CustomCellData {
var isSelected = false
func toggleSelected() {
isSelected = !isSelected
}
}
私は任意のヘルプ、何をすべきか、この上で私の頭を掻くとわからないのです素晴らしいことだ。
これは機能しますが、選択した同じセルのチェックを外したい場合は、どうすればよいでしょうか?同じ場合は 'selectedIndexPath'を' nil'に設定しますか? – Simon
私は答えを更新しました。 Btw: 'CustomCellData'のチェックマークを処理するためのカスタムコードも必要ありません。 – vadian