Таблица с флажком - PullRequest
       1

Таблица с флажком

2 голосов
/ 10 июня 2011

Я использую этот код для просмотра таблицы с флажком.

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) 
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    cell.accessoryType = UITableViewCellAccessoryNone;

            cell.textLabel.text =@"a";
            int flag = (1 << indexPath.row);
            if (_checkboxSelections & flag) 
            {
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            }


    return cell;
}



#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
               _checkboxSelections ^= (1 << indexPath.row);
    [tableView reloadData];
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}

Как узнать, какие ячейки выбраны, а какие нет, когда я нажимаю на какую-то кнопку ?

Ответы [ 4 ]

5 голосов
/ 10 июня 2011

Вы можете использовать следующий метод для доступа к ячейкам таблицы в действии кнопки. И вы можете проверить выбор, используя if (cell.accessoryType == UITableViewCellAccessoryCheckmark) условие, поскольку вы устанавливаете UITableViewCellAccessoryCheckmark для выбранных ячеек.

- (void)onButtonClick {

    int numberOfSections = [tableView numberOfSections];

    for (int section = 0; section < numberOfSections; section++) {

        int numberOfRows = [tableView numberOfRowsInSection:section];

        for (int row = 0; row < numberOfRows; row++) {

            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

            if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {

                // Cell is selected

            } else {

                // Cell is not selected
            }
        }
    }
}
1 голос
/ 21 ноября 2013
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return [array count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"Cell";
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    UIButton   * checkBox=[UIButton buttonWithType:UIButtonTypeCustom];
    checkBox.tag=indexPath.row;
    checkBox.frame=CGRectMake(270,15, 20, 20);
    [cell.contentView addSubview:checkBox];
    [checkBox setImage:[UIImage imageNamed:@"checkbox_not_ticked.png"] forState:UIControlStateNormal];
    [checkBox addTarget:self action:@selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
   }
cell.textLabel.text=[array objectAtIndex:indexPath.row];
return cell;
}

-(void)checkBoxClicked:(id)sender {
  UIButton *tappedButton = (UIButton*)sender;
  if([tappedButton.currentImage isEqual:[UIImage imageNamed:@"checkbox_not_ticked.png"]])
  {
    [sender  setImage:[UIImage imageNamed: @"checkbox_ticked.png"] forState:UIControlStateNormal];
  } else {
    [sender setImage:[UIImage imageNamed:@"checkbox_not_ticked.png"]forState:UIControlStateNormal];
  }
}
0 голосов
/ 10 июня 2011

Вы должны установить вот так

BOOL selected[array count];

тогда

установить значение true для выбранной ячейки (метод didselectrow)

selected[indexPath.row] = !selected[indexPath.row];

при нажатии кнопки вы должны использовать

NSMutableArray *true = [NSMutableArray array];  

for (int i = 0; i < (sizeof(selected) / sizeof(BOOL)); i++) {  
    if (selected[i]) {  
        [true addObject:[Yourarray objectAtIndex:i]];  
    }  
}  
0 голосов
/ 10 июня 2011

Для этого вы должны взять один массив.И когда определенная строка выбрана, вы можете ввести indexpath.row в этот массив.Когда выбрана та же строка, вы можете искать в массиве, эта строка существует, а если она выходит, вы можете удалить флажок из ячейки, а также удалить этот indexpath.row из массива.

Таким образом, вы можетеполучите все выбранные indexpath.row.

Надеюсь, вы получили точку.

Дайте мне знать, если возникнут какие-либо трудности.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...