UITableView一次只能选中一行

时间:2012-04-17 14:11:51

标签: ios xcode ios4 ios5 xcode4

你认为这很容易。使用此代码,我可以检查表中的多行,但我想要的是一次只检查一行。如果用户选择不同的行,那么我希望旧行只是自动取消选中。不知道该怎么做。这是我的代码:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

[tableView deselectRowAtIndexPath:indexPath animated:YES];


UITableViewCell *theCell = [tableView cellForRowAtIndexPath:indexPath];

if (theCell.accessoryType == UITableViewCellAccessoryNone) {
    theCell.accessoryType = UITableViewCellAccessoryCheckmark;
    }

    else if (theCell.accessoryType == UITableViewCellAccessoryCheckmark) {
    theCell.accessoryType = UITableViewCellAccessoryNone;
    }
}

感谢您提供的任何帮助!

17 个答案:

答案 0 :(得分:79)

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath   *)indexPath
{
     [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
}

Swift版本将是:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .Checkmark
}

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .None
}

Swift 3 更新

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

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

答案 1 :(得分:24)

最好的方法是在cellForRowAtIndexPath中设置附件类型,并使用didSelectRowAtIndexPath仅记录选择 的路径,然后调用reloadData。

答案 2 :(得分:22)

您可以创建一个新变量来跟踪在didSelectRowAtIndex选择的索引。

int selectedIndex;
在你的cellForRowAtIndexPath

if(indexPath.row == selectedIndex)
{
   cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
   cell.accessoryType = UITableViewCellAccessoryNone;
}

并在你的didSelectRowAtIndex

selectedIndex = indexPath.row;
[tableView reloadData];

答案 3 :(得分:17)

您不需要(也不应该)在每次选择后重新加载表格。

Apple在如何管理选择列表方面有很好的documentation。有关示例,请参见清单6-3。

这或多或少与其他一些答案相同,但我想我会添加更多细节。

您要做的是将当前选定的IndexPath保存到变量,并在didSelectRowAtIndexPath中使用它来删除旧的复选标记。这也是您添加新复选标记的位置。

您还需要确保在cellForRowAtIndexPath中设置/取消设置复选标记,否则如果列表很大并且单元格被重用,则看起来会选择多行。这是其他一些答案的问题。

请参阅下面的swift 2.0示例:

// for saving currently seletcted index path
var selectedIndexPath: NSIndexPath? = NSIndexPath(forRow: 0, inSection: 0)  // you wouldn't normally initialize it here, this is just so this code snip works
// likely you would set this during cellForRowAtIndexPath when you dequeue the cell that matches a saved user selection or the default

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    // this gets rid of the grey row selection.  You can add the delegate didDeselectRowAtIndexPath if you want something to happen on deselection
    tableView.deselectRowAtIndexPath(indexPath, animated: true) // animated to true makes the grey fade out, set to false for it to immediately go away

    // if they are selecting the same row again, there is nothing to do, just keep it checked
    if indexPath == selectedIndexPath {
        return
    }

    // toggle old one off and the new one on
    let newCell = tableView.cellForRowAtIndexPath(indexPath)
    if newCell?.accessoryType == UITableViewCellAccessoryType.None {
        newCell?.accessoryType = UITableViewCellAccessoryType.Checkmark
    }
    let oldCell = tableView.cellForRowAtIndexPath(selectedIndexPath!)
    if oldCell?.accessoryType == UITableViewCellAccessoryType.Checkmark {
        oldCell?.accessoryType = UITableViewCellAccessoryType.None
    }

    selectedIndexPath = indexPath  // save the selected index path

    // do whatever else you need to do upon a new selection
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
    // if this is the currently selected indexPath, set the checkmark, otherwise remove it
    if indexPath == selectedIndexPath {
        cell.accessoryType = UITableViewCellAccessoryType.Checkmark
    } else {
        cell.accessoryType = UITableViewCellAccessoryType.None
    }
}

答案 4 :(得分:8)

您无需重新加载tableView。

见下面的代码:

为您的类声明NSIndexPath lastSelectedIndexPath变量

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if(lastSelectedIndexPath) {

        UITableViewCell *lastCell = [tableView cellForRowAtIndexPath:lastSelectedIndexPath];
        [lastCell setAccessoryView:nil];
    }

    UITableViewCell *currentCell = [tableView cellForRowAtIndexPath:currentIndexPath];
    [currentCell setAccessoryView:UITableViewCellAccessoryCheckmark];

    lastSelectedIndexPath = indexPath;
}

答案 5 :(得分:4)

我认为https://stackoverflow.com/a/5960016/928599会对你有所帮助 我使用它,它也与deselectRowAtIndexPath一起使用!

答案 6 :(得分:4)

最简单的方法是保存选定的IndexPath并在cellForRowAtIndexPath中进行检查。

附件是代码:

第1步:初始化selectedIndexPath selectedIndexPath = [[NSIndexPath alloc] init];

第2步:在cellForRowAtIndexPath

if([selectedIndexPath isEqual:indexPath]){
    [checkMark setHidden:NO];
} else {
    [checkMark setHidden:YES];
}

第3步:在didSelectRowAtIndexPath

selectedIndexPath = indexPath;
[tableView reloadData];

它应该工作尝试这个Njoy:)

答案 7 :(得分:2)

对于为我工作的Swift 3:

from collections import Counter
list_that_you_seek = main_data.map(lambda x:(x[0],[x[1]])).reduceByKey(lambda x,y:x+y).map(lambda x:(x[0],Counter(x[1])).collect()

答案 8 :(得分:1)

试试这个:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.section == 1 {
        // un-select the older row
        if let selected = self.LastSelected {
            tableView.cellForRowAtIndexPath(selected)?.accessoryType = .None
        }

        // select the new row
        tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.Checkmark
        self.LastSelected = indexPath
    }
}

答案 9 :(得分:1)

在Swift中,以下作品非常完美:

lastSelectedIndexPath = NSIndexPath(forRow: 1, inSection: 0)//Row will be the previous selected row


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell:LabelsSelectionCell = tableView.dequeueReusableCellWithIdentifier("LabelsSelectionCell", forIndexPath: indexPath) as! LabelsSelectionCell
    cell.setCellLael(labelOptionsArray[indexPath.row])
    if lastSelectedIndexPath == indexPath
    {
        cell.setCellCheckedStatus(true)
    }
    return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
    if let _ = lastSelectedIndexPath
    {
        let lastCell:LabelsSelectionCell = tableView.cellForRowAtIndexPath(lastSelectedIndexPath!) as! LabelsSelectionCell
        lastCell.setCellCheckedStatus(false)
    }
    let currentCell:LabelsSelectionCell = tableView.cellForRowAtIndexPath(indexPath) as! LabelsSelectionCell
    currentCell.setCellCheckedStatus(true)

    lastSelectedIndexPath = indexPath

    tableView.deselectRowAtIndexPath(indexPath, animated: true)
}

答案 10 :(得分:0)

Swift iOS

     var checkedIndexPath : NSIndexPath?

     // table row which row was selected
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        println("Section #\(indexPath.section)! You selected cell #\(indexPath.row)!")

        if (self.checkedIndexPath != nil) {
            var cell = tableView.cellForRowAtIndexPath(self.checkedIndexPath!)
            cell?.accessoryType = .None
        }

        var cell = tableView.cellForRowAtIndexPath(indexPath)
        cell?.accessoryType = .Checkmark

        self.checkedIndexPath = indexPath

    }// end tableView

答案 11 :(得分:0)

在Swift 2.0中我使用了这个:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    if((lastSelectedIndexPath) != nil) {
        let lastCell = tableView.cellForRowAtIndexPath(lastSelectedIndexPath)
        lastCell?.accessoryType = UITableViewCellAccessoryType.None
    }

    let currentCell = tableView.cellForRowAtIndexPath(indexPath)
    currentCell?.accessoryType = UITableViewCellAccessoryType.Checkmark

    lastSelectedIndexPath = indexPath

}

答案 12 :(得分:0)

我的方法是在选择期间取消选择其他单元格:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = ....

    if condition {
        cell.accessoryType = .checkmark
        tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.bottom)
    } else {
        cell.accessoryType = .none
    }

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    for row in 0...tableView.numberOfRows(inSection: 0) {
        if row == indexPath.row {continue}
        tableView.deselectRow(at: IndexPath(row: row, section: 0), animated: true)
    }

    if let cell = tableView.cellForRow(at: indexPath) {
        cell.accessoryType = .checkmark
    }
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath)
    cell?.accessoryType = .none
}

答案 13 :(得分:0)

这是我遇到这个问题时出现的问题 此代码在最新版本的Swift中实现,截至今日......
有关详细信息和/或扩展程序文件,请查看此代码段的Github Gist

i = 1

答案 14 :(得分:0)

测试并解决了尝试它完美的工作

  

将其添加为全局变量

var selectedIndexPath = NSIndexPath(row: 0, section: 0)
  

在didselect方法中添加

        // old one check off
        if indexPath != selectedIndexPath as IndexPath {
            let oldCell = categorytable.cellForRow(at: selectedIndexPath as IndexPath)
            if oldCell?.accessoryView != nil {
                oldCell?.accessoryView = nil
            }
            else {
                let imageName = "checkmark"
                let image: UIImageView = UIImageView(image: UIImage(named: imageName))
                cell.accessoryView = image
            }
        }
        // the new one on

        if  cell.accessoryView == nil {
            let imageName = "checkmark"
            let image: UIImageView = UIImageView(image: UIImage(named: imageName))
            cell.accessoryView = image
        }
        else {
            cell.accessoryView = nil
        }

答案 15 :(得分:0)

您可以在一行代码中以自定义单元格类型进行操作。

final class CheckableTableViewCell: UITableViewCell {

  override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    self.accessoryType = selected ? .checkmark : .none
  }

}

要使此方法有效-应该选择您的单元格。

如果您不想看到所选单元格的突出显示,只需在情节提要或代码中将单元格的selectionStyle设置为.none即可。

如果您调用

,则此方法将不起作用
tableView.deselectRow(at: indexPath, animated: true)

也可以很好地进行多重选择。

答案 16 :(得分:0)

Swift 5 版本的 jeffjv 响应。

{{1}}