快速选择每个部分的单元格

时间:2015-05-16 10:04:42

标签: ios uitableview swift cells sections

我在swift中选择多个单元格时遇到了一些问题。

我不想让用户根据需要选择任意数量的单元格,只允许他选择三个单元格(每个部分中有一个)。为了更清楚,我会给你一些代码。

我有三个部分:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 3
}

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! CustomHeaderCell

    /* let  headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as CustomHeaderCell */
 //   headerCell.backgroundColor = UIColor.set(#E6E2E1)

    switch (section) {
    case 0:
        headerCell.headerLabel.text = "Bundesliga";
        //return sectionHeaderView
    case 1:
        headerCell.headerLabel.text = "BBVA";
        //return sectionHeaderView
    case 2:
        headerCell.headerLabel.text = "BPL";
        //return sectionHeaderView
    default:
        headerCell.headerLabel.text = "Other";
    }

    return headerCell
}

我想让每个Club中的用户例如5 League来选择。他必须在每个Club中选择他最喜欢的League。我不想做这样的事情:

tableView.allowsMultipleSelection = true

因为我想在每个部分只允许一个选择。我该如何限制这样的用户?

1 个答案:

答案 0 :(得分:6)

这应该适合你:

override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
    let selectedIndexPaths = indexPathsForSelectedRowsInSection(indexPath.section)

    if selectedIndexPaths?.count == 1 {
        tableView.deselectRowAtIndexPath(selectedIndexPaths!.first!, animated: true)
    }

    return indexPath
}

func indexPathsForSelectedRowsInSection(section: Int) -> [NSIndexPath]? {
    return (tableView.indexPathsForSelectedRows() as? [NSIndexPath])?.filter({ (indexPath) -> Bool in
        indexPath.section == section
    })
}

Swift 4.1的更新 - 带有选定单元格的复选标记

override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    // Find any selected row in this section
    if let selectedIndexPath = tableView.indexPathsForSelectedRows?.first(where: {
        $0.section == indexPath.section
    }) {
        // Deselect the row
        tableView.deselectRow(at: selectedIndexPath, animated: false)
        // deselectRow doesn't fire the delegate method so need to
        // unset the checkmark here
        tableView.cellForRow(at: selectedIndexPath)?.accessoryType = .none
    }
    return indexPath
}

override func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? {
    // Prevent deselection of a cell
    return nil
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}

对于tableView,请确保设置...

allowsMultipleSelection = true
接口生成器

选择:MutlipleSelection

并为每个单元格设置

selectionStyle = .none
Interface Builder中的

选择:无

相关问题