ios ? 选中 UITableViewCell 中的选定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7982944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:10:06  来源:igfitidea点击:

? Checkmark selected row in UITableViewCell

iosuitableview

提问by Suchi

I am an iOS development newbie. I want to add a checkmark to my UITableViewCellwhen it is selected. The checkmark should be removed when another row is selected. How would I do this?

我是 iOS 开发新手。我想在我UITableViewCell被选中时添加一个复选标记。选择另一行时,应删除复选标记。我该怎么做?

回答by Ujwal Manjunath

Do not use [tableview reloadData];// its a hammer.

不要使用[tableview reloadData];// 它是一个锤子。

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

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

回答by 0x8badf00d

In your UITableViewDatasource method:

在您的 UITableViewDatasource 方法中:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell == nil )
    {
        cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    if ([indexPath compare:self.lastIndexPath] == NSOrderedSame) 
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } 
    else 
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}

// UITableView Delegate Method
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.lastIndexPath = indexPath;

    [tableView reloadData];
}

And lastIndexPath is a property(strong) NSIndexPath* lastIndexPath;

而 lastIndexPath 是一个 property(strong) NSIndexPath* lastIndexPath;

回答by Harry Nelken

I found that reloading the data interrupts the deselect animation in an ugly way.

我发现重新加载数据会以一种丑陋的方式中断取消选择动画。

This Swift implementation cleanly adds/removes checkmarks and deselects the row:

这个 Swift 实现干净地添加/删除复选标记并取消选择行:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if self.lastSelection != nil {
        self.myTableView.cellForRowAtIndexPath(self.lastSelection)?.accessoryType = .None
    }

    self.myTableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .Checkmark

    self.lastSelection = indexPath

    self.myTableView.deselectRowAtIndexPath(indexPath, animated: true)
}

where lastSelectionis declared as var lastSelection: NSIndexPath!

其中lastSelection声明为var lastSelection: NSIndexPath!

No extra activity in cellForRowAtIndexPathneeded. Shouldn't be hard to replicate in Obj-C.

不需要额外的活动cellForRowAtIndexPath。在 Obj-C 中复制应该不难。

回答by Jano

To set a checkmark:

要设置复选标记:

UITableViewCell *cell = ...;
cell.accessoryType = UITableViewCellAccessoryCheckmark;

To select/deselect a cell:

要选择/取消选择单元格:

[cell setSelected:TRUE animated:TRUE]; // select
[cell setSelected:FALSE animated:TRUE]; // deselect

To deselect the previous cell use a NSIndexPath *lastSelected ivar to track the last selected cell:

要取消选择上一个单元格,请使用 NSIndexPath *lastSelected ivar 来跟踪最后一个选定的单元格:

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
   if (self.lastSelected==indexPath) return; // nothing to do

   // deselect old
   UITableViewCell *old = [self.tableView cellForRowAtIndexPath:self.lastSelected];
   old.accessoryType = UITableViewCellAccessoryNone;
   [old setSelected:FALSE animated:TRUE];

   // select new
   UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
   cell.accessoryType = UITableViewCellAccessoryCheckmark;
   [cell setSelected:TRUE animated:TRUE];

   // keep track of the last selected cell
   self.lastSelected = indexPath;
}

回答by Singam madhukar

extension ViewController : UITableViewDelegate,UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = dataArray[indexPath.row]
        if selectedData.contains(dataArray[indexPath.row]) {
            cell.accessoryType = .checkmark
        }else{
            cell.accessoryType = .none
        }
        return cell
    }


    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if selectedData.contains(dataArray[indexPath.row]) {
            selectedData.removeLast()
            tableView.cellForRow(at: indexPath)?.accessoryType = .none
        }else {
            selectedData.removeAll()
            selectedData.append(dataArray[indexPath.row])
            tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
        }
        print(selectedData)
    }

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

}

based on dataArray table view formed.. similarly, I took an empty array, and whenever the user taps on a cell, based on indexValue of from dataArray I stored that object in selectedDataArray

基于形成的dataArray表视图..同样,我取了一个空数组,每当用户点击一个单元格时,基于来自dataArray的indexValue我将该对象存储在selectedDataArray中

As for the question its like... A question has multiple options(Answers), But at finally only one or none answer will be a result

至于问题就像......一个问题有多种选择(答案),但最终只有一个答案或没有答案

enter image description here

在此处输入图片说明

Likewise, only one cell should show checkmark and remaining cells should be in unselected... it some case u can deselect your answer... I hope this is the best answer to this question

同样,只有一个单元格应显示复选标记,其余单元格应处于未选中状态……在某些情况下,您可以取消选择您的答案……我希望这是对这个问题的最佳答案

enter image description here

在此处输入图片说明

回答by Puji Wahono

Update Swift 4

更新 Swift 4

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

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

回答by M Murteza

Using Swift 4.2 and swift 5 Working code of check mark for only selected row in TableView

使用 Swift 4.2 和 Swift 5 仅用于 TableView 中选定行的复选标记的工作代码

   func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    self.tableView.cellForRow(at: indexPath)?.accessoryType = .none
}
   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //print(self.coloursArray[indexPath.row])

     self.tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}

回答by Janus Varmarken

Assuming you are in a class that inherits from UITableViewController, this does the trick in Swift 3:

假设您在一个继承自 的类中UITableViewController,这在 Swift 3 中可以实现:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // Add a visual cue to indicate that the cell was selected.
    self.tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
}

override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
    // Invoked so we can prepare for a change in selection.
    // Remove previous selection, if any.
    if let selectedIndex = self.tableView.indexPathForSelectedRow {
        // Note: Programmatically deslecting does NOT invoke tableView(:didSelectRowAt:), so no risk of infinite loop.
        self.tableView.deselectRow(at: selectedIndex, animated: false)
        // Remove the visual selection indication.
        self.tableView.cellForRow(at: selectedIndex)?.accessoryType = .none
    }
    return indexPath
}

回答by Morph

small typo

小错别字

// deselect old
UITableViewCell *old = [self.tableView cellForRowAtIndexPath:self.lastSelected];
cell.accessoryType = UITableViewCellAccessoryNone;
[cell setSelected:FALSE animated:TRUE];

should read

应该读

// deselect old
UITableViewCell *old = [self.tableView cellForRowAtIndexPath:self.lastSelected];
old.accessoryType = UITableViewCellAccessoryNone;
[old setSelected:FALSE animated:TRUE];

and also in the

并且在

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == [previouslySelected intValue])
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        selectedIndex = indexPath;
        [cell setSelected:YES animated:YES];
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [cell setSelected:NO animated:YES];
    }
} 

where previouslySelectedis your local ivar, etc. that way if you reload with a selected index it also gets deselected when you flick through the possible selections.

其中,previousSelected是您的本地 ivar 等,如果您使用选定的索引重新加载,则当您轻弹可能的选择时,它也会被取消选择。

回答by Don Miguel

I think it's cleaner to set the accessory within your custom UITableViewCell implementation. In swift, I have used:

我认为在自定义 UITableViewCell 实现中设置附件更干净。在 swift 中,我使用了:

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

    // Configure the view for the selected state
    accessoryType = selected ? .checkmark : .none
}