UITableViewCell Тип аксессуара отмечен на Tap & Установить другой не отмечен - PullRequest
28 голосов
/ 17 ноября 2009

Я немного запутался в настройках ячеек таблицы настроек.

Я исправил два раздела в моей таблице

  • Главная
  • Office

Что я хочу, так это следовать ...

  • Когда пользователь нажимает на любую ячейку
  • Ячейка выбирается и
    • Я хочу установить флажок (установить тип аксессуара uitableviewcell -checked для подключенной ячейки)
  • А также тип аксессуара для всех остальных ячеек теперь должен быть установлен на
    • тип аксессуара для ячейки с подходящим видом none

Я попробовал следующий код. Но я обнаружил, что indexpath.row & indexpath.section - это свойства только для чтения.

// Override to support row selection in the table view.
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {    
    [tblProfileView deselectRowAtIndexPath:indexPath animated:YES];
    int i,max;
    UITableViewCell *x; NSIndexPath *tt;

    for(i=0;i<[tblProfileView numberOfRowsInSection:0];i++)
    {
        tt.row=i; tt.section=0;
        x=[tblProfileView cellForRowAtIndexPath:];
        [x setAccessoryType:UITableViewCellAccessoryNone];
    }
    for(i=0;i<[tblProfileView numberOfRowsInSection:1];i++)
    {
        tt.row=i; tt.section=1;
        x=[tblProfileView cellForRowAtIndexPath:tt];
        [x setAccessoryType:UITableViewCellAccessoryNone];
    }

    x=[tblProfileView cellForRowAtIndexPath:indexPath];
    [x setAccessoryType:UITableViewCellAccessoryCheckmark];
    // Navigation logic may go here -- for example, create and push another view controller.
    // AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
    // [self.navigationController pushViewController:anotherViewController animated:YES];
    // [anotherViewController release];
}

Ответы [ 9 ]

49 голосов
/ 17 ноября 2009

Я бы следил за данными , которые должны быть проверены, и изменил бы ячейку в tableView: didSelectRowAtIndexPath: и обновил бы, какие данные проверены в tableView: cellForRowAtIndexPath: как это:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // do usual stuff here including getting the cell

    // determine the data from the IndexPath.row

    if (data == self.checkedData)
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // determine the selected data from the IndexPath.row

    if (data != self.checkedData) {
       self.checkedData = data;
    }

    [tableView reloadData];
}
16 голосов
/ 12 марта 2011
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];

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


}

также необходимо удалить аксессуар с галочкой на cellForRowAtIndexPath

if ([selectedOptionsArray indexOfObject:cell.textLabel.text] != NSNotFound) {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else{
    cell.accessoryType = UITableViewCellAccessoryNone;
}
14 голосов
/ 05 сентября 2012

Объявите одну переменную int с именем prev и реализуйте этот метод: -

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

 UITableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];

   if (cell.accessoryType==UITableViewCellAccessoryNone) 
   {
      cell.accessoryType=UITableViewCellAccessoryCheckmark;
      if (prev!=indexPath.row) {
         cell=[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:prev inSection:0]];
         cell.accessoryType=UITableViewCellAccessoryNone;
         prev=indexPath.row;
     }

 }
 else{
     cell.accessoryType=UITableViewCellAccessoryNone;
 }
}
6 голосов
/ 02 января 2014

Самый короткий и простой способ реализовать логику для галочки только в выбранной строке .....


1. Создать глобальный объект NSIndexPath ..

selectedIndexPathForCheckMark= [[NSIndexPath alloc] init];

2. In didSelectRowAtIndexPath ..

// Присвоение выбранного indexPath объявленному объекту

selectedIndexPathForCheckMark = indexPath;  
[tableView reloadData];

3. в cellForRowAtIndexPath ..

if ([selectedIndexPathForCheckMark isEqual:indexPath]) {
    [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}else {
    //setAccessoryType None if not get the selected indexPath
    [cell setAccessoryType:UITableViewCellAccessoryNone];
}
1 голос
/ 11 марта 2015

Я знаю, что этот вопрос довольно старый, но вот версия Swift, основанная на ответе Blackberry (за который я, кстати, проголосовал)

import UIKit

class PlacesViewController: UITableViewController, UITableViewDelegate, UITableViewDataSource {

    var placesArray = NSMutableArray()
    
    var previousCheckedIndex = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.placesArray.addObject("Tandil")
        self.placesArray.addObject("Balcarce")
        self.placesArray.addObject("Mar del Plata")
        
        self.tableView.rowHeight = UITableViewAutomaticDimension
    }

    
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.placesArray.count
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        var cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

        cell.textLabel?.text = self.placesArray.objectAtIndex(indexPath.row) as? String
        

        return cell
    }
    
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        if (indexPath.row != previousCheckedIndex) {
            var cell: UITableViewCell = self.tableView.cellForRowAtIndexPath(indexPath)!
            if (cell.accessoryType == UITableViewCellAccessoryType.None) {
                cell.accessoryType = UITableViewCellAccessoryType.Checkmark
                if (previousCheckedIndex != indexPath.row) {
                    cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: previousCheckedIndex, inSection: 0))!
                    cell.accessoryType = UITableViewCellAccessoryType.None
                    previousCheckedIndex = indexPath.row
                }
            } else {
                cell.accessoryType = UITableViewCellAccessoryType.None
            }
        
            tableView.reloadData()
        }
    }
}
1 голос
/ 16 сентября 2014

Вот как я это делаю со статическими ячейками, минуя cellForRow

Создайте переменную, в которой будет храниться местоположение «проверенной» ячейки.

 NSInteger _checkedCell;

Тогда просто реализуйте willDisplayCell и didSelectRow методы, подобные этим.

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_checkedCell == indexPath.row) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    _checkedCell = indexPath.row;
    [self.tableView reloadData];
}
0 голосов
/ 26 августа 2016

Ответ BlackBerry в Swift 3. UITableView со стандартными ячейками, выбирая 0 или 1 ячейку.

private var previousSelection = NSIndexPath()

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
    let cell = tableView.cellForRow(at: indexPath)!
    if cell.accessoryType == .none {
        cell.accessoryType = .checkmark
        selection = indexPath

        if previousSelection == IndexPath() {
            previousSelection = indexPath
        } else if previousSelection != indexPath {
            let previousCell = tableView.cellForRow(at: previousSelection)
            previousCell?.accessoryType = .none
            previousSelection = indexPath
        }
    } else if cell.accessoryType == .checkmark {
        cell.accessoryType = .none
        selection = IndexPath()
    }

}
0 голосов
/ 13 мая 2016

Учитывая, что вы хотите сохранить только один выбор, и если у вас есть пользовательский UITableViewCell, я бы порекомендовал следующее.

В вашем UITableViewController

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    //... 
    let data = dataArray[indexPath.row]
    if data.isSelected {
        tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None)
    }
    //...

    return cell
}

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let data = dataArray[indexPath.row]
    data.isSelected = true
    let cell = tableView.cellForRowAtIndexPath(indexPath)
    cell?.setSelected(true, animated: true)
}

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let data = dataArray[indexPath.row]
    data.isSelected = false
    let cell = tableView.cellForRowAtIndexPath(indexPath)
    cell?.setSelected(false, animated: true)
}

На заказ UITableViewCell

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

    // Configure the view for the selected state
    self.accessoryType = .None
    if selected {
        self.accessoryType = .Checkmark
    }
}

Пока allowsMultipleSelection не включен, он автоматически обрабатывает отмену выбора других ячеек, когда выбирается новая. Если allowMultipleSelection включен, то он также будет работать, за исключением того, что вам просто нужно снова нажать, чтобы отменить выбор.

0 голосов
/ 24 ноября 2015

В Swift 2.0 с помощью пользовательского аксессуара. Просмотр uitableviewcell с помощью swift

1º Создание Globar var IndexPath

var indexSelected = NSIndexPath()

2º In didSelectRowAtIndexPath

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        indexSelected = indexPath
        TB_Lojas.reloadData()
    }

3º в ячейкеForRowAtIndexPath:

if SelectedIndexPath == indexPath {
                let img = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
                img.image = UIImage(named: "check")
                cell.accessoryView = img
            }else{
                let img = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
                img.image = UIImage(named: "uncheck")
                cell.accessoryView = img
            }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...