Checkmark on static cells uitableview

非 Y 不嫁゛ 提交于 2020-01-12 05:12:08

问题


I'm using a UITableView, with 3 sections ( Static Cells )

  • Currency
  • Language
  • Social

They have different number of rows:

  • Currency has 3 rows ( USD, EUR, JPY )
  • Language has 2 rows ( EN, JP )
  • Social has 3 rows ( Twitter, FB, Line )

Right now, I have by default set a checkmark at the first row of every section. However, I would like to allow the user to set their default settings and change the checkmark accordingly based on what they have set.

My question is then how do I set the checkmark for 3 different sections each with varying number of rows?

Do I need to set an cell identifier for each Section? Do I also need to create a UITableViewCell swift file for each Section?


回答1:


If the checkmarks are set in response to tapping on the cell, just implement tableView(_:didSelectRowAtIndexPath:):

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let section = indexPath.section
    let numberOfRows = tableView.numberOfRowsInSection(section)
    for row in 0..<numberOfRows {
        if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: row, inSection: section)) {
            cell.accessoryType = row == indexPath.row ? .Checkmark : .None
        }
    }
    // ... update the model ...
}

Otherwise, you can set identifiers for each cell in your storyboard (or outlets if you prefer, since the cells aren't reused), and then just set the checkmark programmatically. For example, using a delegate method:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    if let identifier = cell.reuseIdentifier {
        switch identifier {
            "USD Cell": cell.accessoryType = model.usdChecked ? .Checkmark : .None
            "EUR Cell": cell.accessoryType = model.eurChecked ? .Checkmark : .None
            //...
            default: break
        }
    }
}

There shouldn't be a need to create a separate subclass for each section/cell.




回答2:


Just a quick update for Swift 3:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let section = indexPath.section
        let numberOfRows = tableView.numberOfRows(inSection: section)
        for row in 0..<numberOfRows {
            if let cell = tableView.cellForRow(at: IndexPath(row: row, section: section)) {
                cell.accessoryType = row == indexPath.row ? .checkmark : .none
            }
        }
}


来源:https://stackoverflow.com/questions/29407723/checkmark-on-static-cells-uitableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!