ios - 快速表格 View 向单元格添加自定义复选标记并从上一个单元格中删除复选标记

标签 ios swift uitableview

我的单元格中有一个 ImageView ,它显示一个复选标记图标。

我想要做的是,当您触摸一个单元格时,复选标记应该出现。我得到了这个工作,但我现在的问题是我无法从以前选择的单元格中删除复选标记。 - 只能选择一个单元格。

我已尝试在 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)
    }

最佳答案

  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
    }
    

需要注意的重要一点是,选择哪一行的状态应该存储在模型中而不是单元格中。该表应反射(reflect)模型的状态。在这种情况下,模型可以只是所选行的 indexPath。模型更新后(selectedRow 已设置),受影响的行应重新加载其状态。

关于ios - 快速表格 View 向单元格添加自定义复选标记并从上一个单元格中删除复选标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32162186/

相关文章:

iOS:如何在 Storyboard中实际没有单元格的情况下将可重用的 'default' 单元格出列

Swift - 以相同的方式配置不同的单元格

c# - 如何在Push Sharp库的APNS有效负载中添加类别以进行交互式通知iOS

ios - 单击按钮时在Swift中不重复单词-iOS

ios - 嵌入式 UINavigationController Storyboard问题

ios - Xcode 在没有任何改变时重建项目

swift - PromiseKit 语法链 swift

ios - 在 iOS 5 上关闭 UIImagePickerController 后出现白屏?

swift - 当主类的父类(super class)是 UICollectionViewCell 时,如何执行Segue或从单元格转到另一个 View

ios - UIAppearance 更改 UITableView backgroundView 导致主线程崩溃