Пользовательский TableViewCell не обновляется - PullRequest
0 голосов
/ 02 ноября 2011

Я хочу установить галочку перед ячейкой. Когда я нажимаю на значок галочки, вызывается правильная функция и источник данных изменяется.

My Custom cell

Я вызываю [таблица reloadData] , и после этого вызывается даже cellForRowAtIndexPath , но он всегда удаляет старую ячейку таблицы и не перезагружает ее с новым источником данных ..

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"CheckboxCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

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

// use CustomCell layout 
CheckboxCell *checkboxCell;

if(cell == nil) {
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CheckboxCell" owner:self options:nil];

    for (id currentObject in topLevelObjects){
        if ([currentObject isKindOfClass:[UITableViewCell class]]){
            checkboxCell =  (CheckboxCell *)currentObject;
            break;
        }
    }
} else {
    checkboxCell =  (CheckboxCell *)cell; // return cell;
}

Observation *observation = [observations objectAtIndex:indexPath.row];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd.MM.yyyy";
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSString *nowString = [dateFormatter stringFromDate:observation.date];
[dateFormatter release];

NSString *amountString = [[NSString alloc] initWithFormat:@"%d", observation.amount];

checkboxCell.name.text = [observation.organism getNameDe];
checkboxCell.date.text = nowString;
checkboxCell.amount.text = amountString;
checkboxCell.latName.text = [observation.organism getLatName];

// Define the action on the button and the current row index as tag
[checkboxCell.checkbox addTarget:self action:@selector(checkboxEvent:) forControlEvents:UIControlEventTouchUpInside];
[checkboxCell.checkbox setTag:observation.observationId];

// Define the action on the button and the current row index as tag
[checkboxCell.remove addTarget:self action:@selector(removeEvent:) forControlEvents:UIControlEventTouchUpInside];
[checkboxCell.remove setTag:observation.observationId];

// Set checkbox icon
if(observation.submitToServer) {
    NSLog(@"CHECKED");
    checkboxCell.checkbox.imageView.image = [UIImage imageNamed:@"check_icon.png"];
} else {
    NSLog(@"UNCHECKED");
    checkboxCell.checkbox.imageView.image = [UIImage imageNamed:@"checkbox.gif"];
}

[amountString release];
[observation release];

return checkboxCell;


// Set checkbox icon
if(observation.submitToServer) {
    NSLog(@"CHECKED");
    checkboxCell.checkbox.imageView.image = [UIImage imageNamed:@"check_icon.png"];
} else {
    NSLog(@"UNCHECKED");
    checkboxCell.checkbox.imageView.image = [UIImage imageNamed:@"checkbox.gif"];
}

[amountString release];
[observation release];

return checkboxCell;

}

Я думаю, что я делаю что-то в cellForRowAtIndexPath неправильно .. Кто-нибудь может мне помочь?

Edit:

Первая проблема может быть исправлена ​​ (Спасибо Мэгги) . Теперь галочка меняется с первого раза правильно. Но каким-то образом, если я изменю его в другой ячейке, он вылетает в следующей строке:

- (void) checkboxEvent:(UIButton *)sender
{
UIButton *button = (UIButton *)sender;
NSNumber *number = [NSNumber numberWithInt:button.tag];

for(Observation *ob in observations) {

    if(ob.observationId == [number intValue]) { // <---- IT'S CRASHING HERE
        ob.submitToServer = !ob.submitToServer;

        NSLog(@"New value: %@", (ob.submitToServer) ? @"YES" : @"NO");
    }
}

[table reloadData];
}

Но объект наблюдения не ноль. Есть идеи?

1 Ответ

2 голосов
/ 02 ноября 2011

Замените

 else {
    return cell;
}

деталь на

 else {
    checkboxCell =  (CheckboxCell *)cell;
 }

и заполните флажок ячейки соответствующими данными.

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