Проблема с настройкой изображения значка в ячейке - PullRequest
1 голос
/ 06 июня 2011

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

Я создал подкласс UIButton, как показано ниже

//.h file
@interface Bleh : UIButton {

}

+(id)specialInit;
-(void)vvv;

@end

//.m file
@implementation Bleh

+(id) specialInit
{
    Bleh* button=[super buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"blank_star.png"] forState:UIControlStateNormal];    
    [button setImage:[UIImage imageNamed:@"star.png"] forState:UIControlStateDisabled];    
    [button addTarget:button action:@selector(vvv)    forControlEvents:UIControlEventTouchUpInside];    
    NSLog(@"%d",[button isEnabled]);
    return button;
}


-(void)vvv
{
    NSLog(@"button tapped");
    [self setEnabled:false];
}

@end

Я добавил подкласс UIButton в метод cellforRow: моего табличного представления следующим образом:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    int row = indexPath.row;
    NSString *cc = [array objectAtIndex:row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        // Configure the cell...    
        Bleh *button = [Bleh specialInit];
        button.frame = CGRectMake(0, 0, 100, 100);
        NSLog(@"Button:%@ at row number: %i",button, indexPath.row);

        cell.textLabel.text = cc;
        [cell.contentView addSubview:button];

    }
    return cell;
}

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

enter image description here

Странно то, что после прокрутки вниз я вижу и другие клетки со сплошной звездой (см. Клетку 'e').

enter image description here

Может кто-нибудь помочь объяснить, почему это происходит? Кажется, что state ячейки повторно используется в других ячейках. Как я могу избежать этого?

Ответы [ 2 ]

1 голос
/ 06 июня 2011

Вы можете сохранить состояние кнопки в NSMutableArray, и когда вы рисуете установленную ячейку, если она включена или отключена на основе NSMutableArray.Чтобы изменить значение в массиве, вы должны пометить ячейку и внести изменения в ваш селектор vvv.

//.h file
@interface Bleh : UIButton {
    NSMutableArray *data;
}

В вашей функции

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ...
    // Configure the cell...    
    Bleh *button = [Bleh specialInit];
    [button setTag:row] // row is the id of the button
    if([data objectAtIndex:row] isEqualToString:@"ENABLED"]) [button setEnabled:TRUE];
    else [button setEnabled:FALSE];
    ...
}

В вашем селекторе vvv

-(void)vvv:(id)sender {
    if([sender isEnabled]) {
        [sender setEnabled:FALSE];
        [data replaceObjectAtIndex:[sender tag] withObject:@"DISABLED"];
    }
    else {
        [sender setEnabled:TRUE];
        [data replaceObjectAtIndex:[sender tag] withObject:@"ENABLED"];

    }
}

И вы должны инициировать массив в вашем viewDidLoad, скажем, для 10 ячеек

- (void)viewDidLoad
{
    ...
    data = [[NSMutableArray alloc] initWithCapacity:10];
    for ( int i = 0; i < 10; i++ ) {
        [data addObject:@"ENABLED"];
    }
    ...
}
1 голос
/ 06 июня 2011

Клетки используются повторно. У меня тоже когда-то была эта проблема. Это может быть немного больше памяти, так как не удаляет старые ячейки из памяти, но делает кодирование проще. Один трюк состоит в том, чтобы сделать это:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row = indexPath.row;
    NSString *CellIdentifier = [NSString stringWithFormat@"Cell %i", row];
    NSString *cc = [array objectAtIndex:row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        // Configure the cell...    
        Bleh *button = [Bleh specialInit];
        button.frame = CGRectMake(0, 0, 100, 100);
        NSLog(@"Button:%@ at row number: %i",button, indexPath.row);

        cell.textLabel.text = cc;
        [cell.contentView addSubview:button];

    }
...