Подтвердить что ты не робот

Тип аксессуара UITableViewCell, проверенный на доступ и установка других непроверенных

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

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

  • Главная
  • Управление

Чего я хочу, как следует...

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

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

// 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];
}
4b9b3361

Ответ 1

Я бы отслеживал данные, которые нужно проверить, и изменить ячейку в tableView: didSelectRowAtIndexPath: и обновить, какие данные отмечены в таблицеView: 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];
}

Ответ 2

- (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;
}

Ответ 3

Объявить одну переменную 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;
 }
}

Ответ 4

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


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

selectedIndexPathForCheckMark= [[NSIndexPath alloc] init];

2. В файле 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];
}

Ответ 5

Здесь, как я делаю это со статическими ячейками и обходя cellForRow

Создайте var, в котором хранится местоположение ячейки "checked".

 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];
}

Ответ 6

Я знаю, что этот вопрос довольно старый, но вот версия 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()
        }
    }
}

Ответ 7

В Swift 2.0, используя пользовательский аксессуар uitableviewcell со скоростью

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

var indexSelected = NSIndexPath()

2º В файле didSelectRowAtIndexPath

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

3º в cellForRowAtIndexPath:

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
            }
}

Ответ 8

Учитывая, что вы хотите сохранить только один выбор, и если у вас есть пользовательский 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 включен, значит, он будет работать, за исключением того, что вам просто нужно нажать еще раз, чтобы отменить выбор.

Ответ 9

Ответ 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()
    }

}