проблема сброса флажка uitableview - PullRequest
0 голосов
/ 04 апреля 2011

У меня есть uitableview с 20 строками, в котором показано несколько продуктов.

Каждый элемент питания имеет флажок вместе с ним.

Моя проблема: если я проверяю первую строку флажка, а затем прокручиваю вид таблицы, флажок сбрасывается.

Как я могу решить эту проблему? Пожалуйста, помогите мне.

Обновление кода:

- (IBAction)buttonAction:(id)sender
{
  if ([sender isKindOfClass:[UIButton class]])
  {
    UIButton *checkboxButton = (UIButton*)sender;

    checkboxButton.selected = !checkboxButton.selected;

    NSIndexPath *indexPath = [self.myTableView indexPathForCell:(UITableViewCell*)[[checkboxButton superview] superview]];

    BOOL selected = [[selectedArray objectAtIndex:[indexPath row]] boolValue];

    [selectedArray replaceObjectAtIndex:[indexPath row] withObject:[NSNumber numberWithBool:!selected]];

      if (!self.checkedIndexPaths)
          checkedIndexPaths = [[NSMutableSet alloc] init];

    if(selected == NO)
    {
          NSLog(@"cvbcvbNO BOOL value");    // ...

        //  If we are checking this cell, we do
        [self.checkedIndexPaths addObject:indexPath];
    }
    else
    {
      NSLog(@"cvbvbYES BOOL VALURE");

        //  If we are checking this cell, we do
        [self.checkedIndexPaths removeObject:indexPath];
    }



  }
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

  static NSString *CellIdentifier = @"Celhgl";

  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  profileName = [appDelegate.sentItemsList objectAtIndex:indexPath.row];

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

        cb = [[UIButton alloc] initWithFrame:CGRectMake(5,10, unselectedImage.size.width, unselectedImage.size.height)];
        [cb setImage:unselectedImage forState:UIControlStateNormal];
        [cb setImage:selectedImage forState:UIControlStateSelected];
        [cb addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchDown];
        [cell.contentView addSubview:cb];

        for (NSIndexPath *path in self.checkedIndexPaths)
        {
            NSLog(@"%d",path.row);

            NSLog(@"%d",indexPath.row);

           if (path.row == indexPath.row)
          {
            NSLog(@"dfd %d",indexPath.row);
          }
        }

   }

    if ( tableView == myTableView )
    {
        titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 0, 150, 35)];
        titleLabel.font = [UIFont boldSystemFontOfSize:13];
        titleLabel.textColor = [UIColor blackColor];   
        [cell.contentView addSubview:titleLabel];
        NSString *subjectData = [profileName.sent_subject stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
        [titleLabel setText:[NSString stringWithFormat: @"%@ ", subjectData]];
    }

    return cell;
}

Ответы [ 2 ]

5 голосов
/ 04 апреля 2011

Что происходит, так это то, что UITableView перерабатывает UITableViewCells для экономии памяти. Это означает, что когда вы прокручиваете список вниз, UITableView снимает ячейки с верхней части таблицы и использует их для отображения более поздних элементов, поэтому при прокрутке вверх они потеряли состояние.

Вы можете исправить это, сохранив NSMutableSet проверенных indexPaths. Когда пользователь проверяет элемент, вы добавляете его indexPath к этому набору. Затем в вашем cellForRowAtIndexPath вы можете проверить, есть ли этот элемент в вашем наборе отмеченных элементов.

UPDATE

Вот пример того, как это может работать:

# MyTableView.h

@interface MyTableView: UITableView
<UITableViewDataSource, UITableViewDelegate>
{
  NSMutableSet *checkedIndexPaths;
}

@property (nonatomic, retain) NSMutableSet *checkedIndexPaths;

@end

тогда

# MyTableView.m
#import "MyTableView.h"

@implementation MyTableView

@synthesize checkedIndexPaths;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  //  Normal layout stuff goes here...
  //  ***Add code to make sure the checkbox in this cell is unticked.***

  for (NSIndexPath *path in self.checkedIndexPaths)
  {
    if (path.section == indexPath.section && path.row == indexPath.row)
    {
      //  ***We found a matching index path in our set of checked index paths, so we need to show this to the user by putting a tick in the check box, for instance***
    }
  }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  //  Normal stuff to handle visual checking/unchecking of row here

  //  Lazy-load the mutable set
  if (!self.checkedIndexPaths)
    checkedIndexPaths = [[NSMutableSet alloc] init];

  //  If we are checking this cell, we do
  [self.checkedIndexPaths addObject:indexPath];

  //  If we are unchecking, just enumerate over the items in checkedIndexPaths and remove the one where the row and section match.
}

@end

Это всего лишь скелетный код, который не тестировался, но, надеюсь, даст вам шанс.

5 голосов
/ 04 апреля 2011

сохранить отмеченные элементы в вашем источнике данных.

Обычно я сохраняю NSIndexPaths выбранных объектов в NSMutableSet.
И в tableView:cellForRowAtIndexPath: проверяю, является ли indexpath частьюнабор с выбранными индексными путями.

@interface RootViewController : UITableViewController {
    NSMutableSet *set;
}

// implementation:

- (void)viewDidLoad {
    [super viewDidLoad];
    set = [[NSMutableSet alloc] init];
}

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

    // Configure the cell.
    cell.textLabel.text = [NSString stringWithFormat:@"Cell %d", indexPath.row];
    if ([set containsObject:indexPath]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([set containsObject:indexPath]) {
        [set removeObject:indexPath];
    }
    else {
        [set addObject:indexPath];
    }
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...