выбор ячейки tableView на iphone - PullRequest
       3

выбор ячейки tableView на iphone

2 голосов
/ 06 октября 2011

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

Для этого я сделал следующее:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableViewMieux deselectRowAtIndexPath:indexPath animated:YES];

    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];

    if (selectedCell.accessoryType == UITableViewCellAccessoryNone)
    {
        UIImageView *checkBox = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkbox-pressed.png"]] autorelease];
        checkBox.frame = CGRectMake(0, 0, 20, 20);
        selectedCell.accessoryView = checkBox;  
        selectedCell.accessoryType=UITableViewCellAccessoryCheckmark;
    }    
    else  if (selectedCell.accessoryType==UITableViewCellAccessoryCheckmark)     
        {
            UIImageView *checkBox = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkbox.png"]] autorelease];
            checkBox.frame = CGRectMake(0, 0, 20, 20);
            selectedCell.accessoryView = checkBox;
            selectedCell.accessoryType=UITableViewCellAccessoryNone;
        }   
    [tableViewMieux  reloadData];
}

Все отлично работает, за исключением того факта, что когда я выбираю первую ячейку, она помечается галочкой, а пятая ячейка тоже автоматически помечается.И так далее ... если я выберу вторую ячейку, это будет помечено галочкой ... и будет помечена другая ячейка в нижней части tableView.

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

Question:Why?What is the right way to do it?

РЕДАКТИРОВАТЬ:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableViewMieux dequeueReusableCellWithIdentifier:@"CellRecherchePartenaires"];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"CellRecherchePartenaires"] autorelease];

        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.backgroundView.opaque = NO;

        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.opaque = NO;
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.highlightedTextColor = [UIColor whiteColor];
        cell.textLabel.font = [UIFont boldSystemFontOfSize:15];

        cell.detailTextLabel.backgroundColor = [UIColor clearColor];
        cell.detailTextLabel.opaque = NO;
        cell.detailTextLabel.textColor = [UIColor whiteColor];
        cell.detailTextLabel.highlightedTextColor = [UIColor whiteColor];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:15];

        cell.accessoryView=UITableViewCellAccessoryNone;

    }

    // Set up the cell...
    [[cell textLabel] setText: [tableArray objectAtIndex:indexPath.row]] ;

    return cell;
}

Ответы [ 5 ]

2 голосов
/ 06 октября 2011

добавить следующие строки

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


if([[tableView cellForRowAtIndexPath:indexPath] accessoryType] == UITableViewCellAccessoryCheckmark)
  {
      temp = [myarray objectAtInadex:indexpath.row];// change the line according to ur code

   //temp is any object.. //array is nsmutable array(global)
   [array removeObject:temp];

   [tableView cellForRowAtIndexPath:indexPath].accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]] autorelease];
   [[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryNone];
   return;
  }
  else
  {
//temp is any objecct....//arry is nsmutable array(global)
   [array addObject:temp];   
   [tableView cellForRowAtIndexPath:indexPath].accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"4.png"]] autorelease];
   [[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark];


  }
 }

}

В ячейке для пути индекса строки

 temp = [myarray objectAtInadex:indexpath.row];// change the line according to ur code
    if ([array containsObject:temp]) {
      cell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"4.png"]] autorelease];

      [[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark];
     }
     else 
     {
      cell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]] autorelease];
      [[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryNone];
     }

В числе строк В разделе

[array removeAllObjects];

Попробуйте, это будет работать.уверен

1 голос
/ 07 октября 2011
   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
     {
    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d%d", indexPath.section, indexPath.row];
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    cell.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    cell.backgroundView.opaque = NO;

    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.textLabel.opaque = NO;
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.highlightedTextColor = [UIColor whiteColor];
    cell.textLabel.font = [UIFont boldSystemFontOfSize:15];

    cell.detailTextLabel.backgroundColor = [UIColor clearColor];
    cell.detailTextLabel.opaque = NO;
    cell.detailTextLabel.textColor = [UIColor whiteColor];
    cell.detailTextLabel.highlightedTextColor = [UIColor whiteColor];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:15];

    cell.accessoryView=UITableViewCellAccessoryNone;

}

// Set up the cell...
[[cell textLabel] setText: [tableArray objectAtIndex:indexPath.row]] ;

return cell;

}

Просто попробуйте это ...

0 голосов
/ 06 октября 2011

На вопрос, почему это так:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

Этот метод, который вы вызываете здесь: UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath]; возвращает ячейку, но apple разработал ее так, чтобы ячейки не создавались с нуля каждый разскорее, ячейки используются повторно, поэтому ваша 5-я и 20-я ячейки в табличном представлении могут быть «одинаковыми», потому что при прокрутке вниз ячейка освобождается, когда она выходит из поля зрения, а те, к которым вы прокручиваете, создаются при прокрутке.таким образом, для просмотра таблицы используется меньше памяти.

Что касается решения этой проблемы, я не уверен, но вы должны ... по-видимому, посмотреть на решение mrd3650, которое он выложил, когда янабрав:)

0 голосов
/ 06 октября 2011

Я добавил еще один ответ для ясности ...

Я сделал комментарии //--Added--->, где я отредактировал.

Если есть что-то непонятное, оставьте комментарий.

Обратите внимание, что self.currentlySelected должно быть объявлено как свойство NSString (может быть приватным)

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableViewMieux deselectRowAtIndexPath:indexPath animated:YES];

    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];

    if (selectedCell.accessoryType == UITableViewCellAccessoryNone)
    {
        UIImageView *checkBox = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkbox-pressed.png"]] autorelease];
        checkBox.frame = CGRectMake(0, 0, 20, 20);
        selectedCell.accessoryView = checkBox;  
        selectedCell.accessoryType=UITableViewCellAccessoryCheckmark;
    }    
    else  if (selectedCell.accessoryType==UITableViewCellAccessoryCheckmark)     
        {
            UIImageView *checkBox = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checkbox.png"]] autorelease];
            checkBox.frame = CGRectMake(0, 0, 20, 20);
            selectedCell.accessoryView = checkBox;
            selectedCell.accessoryType=UITableViewCellAccessoryNone;
        }   

//-----ADDED---->>

int idx = [tableArray indexOfObject:self.currentlySelected];
if (idx != indexPath.row) 
    cell.accessoryType = UITableViewCellAccessoryNone;
else
    cell.accessoryType = UITableViewCellAccessoryCheckmark;

//-----ADDED----<<

    [tableViewMieux  reloadData];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableViewMieux dequeueReusableCellWithIdentifier:@"CellRecherchePartenaires"];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"CellRecherchePartenaires"] autorelease];

        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.backgroundView.opaque = NO;

        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.opaque = NO;
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.highlightedTextColor = [UIColor whiteColor];
        cell.textLabel.font = [UIFont boldSystemFontOfSize:15];

        cell.detailTextLabel.backgroundColor = [UIColor clearColor];
        cell.detailTextLabel.opaque = NO;
        cell.detailTextLabel.textColor = [UIColor whiteColor];
        cell.detailTextLabel.highlightedTextColor = [UIColor whiteColor];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:15];

        cell.accessoryView=UITableViewCellAccessoryNone;

    }

    // Set up the cell...
    [[cell textLabel] setText: [tableArray objectAtIndex:indexPath.row]] ;

//----ADDED--->>
// Save currently selected text - NOTE this must be a property
self.currentlySelected = [tableArray objectAtIndex:indexPath.row];
//----ADDED---<<

    return cell;
}
0 голосов
/ 06 октября 2011

У меня тоже была эта проблема. Скорее всего, это потому, что вы повторно используете ячейки (с идентификатором ячейки. Именно это вы и должны делать). Чтобы решить это, в делегате

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

сделать следующее:

static NSString * cellIdentifier = @"Cell";

// Get reusable cell if possible
UITableViewCell * cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                   reuseIdentifier:cellIdentifier] autorelease];
}

// Remove checkmark if cell is not the one that should be checked
int idx = [workingDatasource indexOfObject:currentSupposedToBeChecked];
if (idx != indexPath.row) 
    cell.accessoryType = UITableViewCellAccessoryNone;
else
    cell.accessoryType = UITableViewCellAccessoryCheckmark;

РЕДАКТИРОВАТЬ: больше объяснений:

Итак, workingDatasource - это массив, который содержит источник данных UITableView, а currentSuppposedToBeChecked - это переменная экземпляра, содержащая фактические данные (которая должна быть одной из данных в источнике данных ) это должно быть проверено.

Таким образом, при каждом касании (т. Е. В didSelectRowAtIndexPath: делегате) вы должны сохранять выбранный объект, выполняя

self.currentSupposedToBeChecked = [workingDatasource objectAtIndex:indexPath.row];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...