2012-03-28 4 views
2

Обновлено моего вопросаReload табличные не работает

Я получил страницу настроек, где я показываю имя настройки на левом, и то, что текущее значение параметра справа (UITableViewCellStyleValue1). Когда вы нажимаете ячейку настройки, вы получаете лист действий, который позволяет выбрать «Просмотреть все», «Да», «Нет». Моя цель - поместить значение, которое они выбирают в правую часть ячейки, чтобы они могли видеть изменение.

Действие Лист событий

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { 
    if (buttonIndex == 0) { 
     thisVal = @"Show All"; 
     NSLog(@"Button 0"); 
    } else if (buttonIndex == 1) { 
     thisVal = @"Yes"; 
     NSLog(@"Button 1"); 
    } else if (buttonIndex == 2) { 
     thisVal = @"No"; 
     NSLog(@"Button 2"); 
    } else if (buttonIndex == 3) { 
     NSLog(@"Button 3"); 
    } 

    [self saveSettings:thisKey :thisVal]; 

    NSLog(@"Before: %@",[table2settings objectAtIndex:(NSUInteger)thisRow]); 

    if (thisSection == 0){ 
     [table1settings replaceObjectAtIndex:(NSUInteger)thisRow withObject:thisVal]; 
    }else{ 
     [table2settings replaceObjectAtIndex:(NSUInteger)thisRow withObject:thisVal]; 
    } 

    NSLog(@"After: %@",[table2settings objectAtIndex:(NSUInteger)thisRow]); 

    [self.tblView reloadData]; 
} 

Из-за Before и After NSLog, я могу видеть, что фактический массив обновляется. Но tblView не перезагружается. данные.

cellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier; 
    if (indexPath.row == 0 && indexPath.section == 0){ 
     CellIdentifier = @"CellWithSwitch"; 
    }else{ 
     CellIdentifier = @"PlainCell"; 
    } 


    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier]; 
    } 

    if (indexPath.section == 0){ 
     [[cell textLabel] setText:[table1labels objectAtIndex:indexPath.row]]; 
     if (indexPath.row == 0 && indexPath.section == 0){ 
      BOOL switchOn; 
      if ([[table1settings objectAtIndex:indexPath.row] isEqualToString: @"On"]){ 
       switchOn = YES; 
      }else{ 
       switchOn = NO; 
      } 

      switchview = [[UISwitch alloc] initWithFrame:CGRectZero]; 
      [switchview setOn:switchOn animated:YES]; 
      [switchview addTarget:self action:@selector(updateCurrentLocation) forControlEvents:UIControlEventValueChanged]; 
      cell.accessoryView = switchview; 
     }else{ 

      if (![[table1settings objectAtIndex:indexPath.row] isEqualToString: @""]){ 
       [[cell detailTextLabel] setText:[table1settings objectAtIndex:indexPath.row]]; 
      }else{ 
       [[cell detailTextLabel] setText:@""]; 
      } 
     } 
    }else{ 
     if (![[table2settings objectAtIndex:indexPath.row] isEqualToString: @""]){ 
      [[cell detailTextLabel] setText:[table2settings objectAtIndex:indexPath.row]]; 
     }else{ 
      [[cell detailTextLabel] setText:@""]; 
     } 
     [[cell textLabel] setText:[table2labels objectAtIndex:indexPath.row]]; 

    } 

    return cell; 
} 

Дополнительная информация

Вот @interface моего .h файла:

NSMutableArray *table1settings; 
NSMutableArray *table2settings; 

И под этим:

@property (nonatomic, retain) NSMutableArray *table1labels; 
@property (nonatomic, retain) NSMutableArray *table2labels; 

И мой .m файл:

@synthesize table1settings; 
@synthesize table2settings; 

updateCurrentLocation

- (void)updateCurrentLocation { 
    switchview.on ? [self saveSettings:@"useLocation" :@"On"] : [self saveSettings:@"useLocation" :@"Off"]; 
    NSLog(@"%@", [self loadSettings:@"useLocation"]); 
} 

Еще раз

@interface DOR_FiltersViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate> 
UITableView *tblView; 
@property (nonatomic, retain) UITableView *tblView; 
@synthesize tblView; 

Кроме того, для @implementation DOR_FiltersViewController, я получаю предупреждение о том, " Неполное осуществление ntation». Я понятия не имею, что может означать это общее утверждение. Пытался найти его, и похоже, что это может означать что угодно.

Исправление

Во-первых, я обнаружил, что у меня не было tblView подключен к моему табличном. -.- Мне пришлось щелкнуть правой кнопкой мыши по представлению таблицы и перетащить его в файл .h и связать его с tblView. Я думал, что уже сделал это. Теперь я чувствую себя очень глупо. Затем, для @interface, мне пришлось использовать __weak IBOutlet UITableView *tblView;, а под этим @property (weak, nonatomic) IBOutlet UITableView *tblView; Тогда все сработало.

+4

Перезагрузка стола не будет эффективной t, если вы не обновили модель данных - код, который вам нужно включить, будет вашим методом cellForRowAtIndexPath и тем, что запускается, когда лист действий вызывается/отклоняется. – jrturton

+0

Пожалуйста, разместите обратный вызов actionSheet и обратный вызов cellForRowAtIndexPath. – Mat

+0

Что вы имеете в виду, вы больше не используете 'cellForRowAtIndexPath:'? –

ответ

2

Две вещи: table1settings и table2settings должны быть NSMutableArray, хотя, согласно ошибке, вы получаете это не проблема.

Похоже, thisVal - это iVar вашего класса.Вы должны размещать его внутри clickedButtonAtIndex:

Попробуйте это:

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { 

    NSString *thisVal; //this line was added 

    if (buttonIndex == 0) { 
     thisVal = @"Show All"; 
     NSLog(@"Button 0"); 
    } else if (buttonIndex == 1) { 
     thisVal = @"Yes"; 
     NSLog(@"Button 1"); 
    } else if (buttonIndex == 2) { 
     thisVal = @"No"; 
     NSLog(@"Button 2"); 
    } else if (buttonIndex == 3) { 
     NSLog(@"Button 3"); 
    } 

    [self saveSettings:thisKey :thisVal]; 

    if (thisSection == 0){ 
     NSLog(@"thisRow is %d and table1settings has %d elements", thisRow, [table1settings count]); 
     [table1settings replaceObjectAtIndex:(NSUInteger)thisRow withObject:thisVal]; 
    }else{ 
     NSLog(@"thisRow is %d and table2settings has %d elements", thisRow, [table2settings count]); 
     [table2settings replaceObjectAtIndex:(NSUInteger)thisRow withObject:thisVal]; 
    } 
    [self.tblView reloadData]; 
} 

И, конечно, удалить другую реализацию thisVal (вероятно, в @interface части).

отметить также, что replaceObjectAtIndex: имеет следующую структуру:

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject 

Там должна быть простой NSUinteger для index.

EDIT:

Если вы звоните [self.tblView reloadData]; не инициирует никаких cellForRowAtIndexPath: вызовов, то self.tblView не ссылается должным образом.

EDIT 2:

Убедитесь, что в классе, где - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath ложь принимает UITableViewDataSource протокол.

Вы можете сделать это в .h файле, например:

@interface YourClass:UIViewController <UITableViewDataSource> 

И вы должны позволить table знать, кто ее dataSource есть. В коде, вы установите порог

self.tblView = thatTable; 

добавить

self.tblView.dataSource = self; 

И если вы используете какие-либо из UITableViewDelegate методов, которые вы должны бросить, что в смесь:

@interface YourClass:UIViewController <UITableViewDataSource,UITableViewDelegate> 

и

self.tblView.delegate = self; 
+0

@James: Не могли бы вы также опубликовать 'updateCurrentLocation method'? –

+0

@James: вы, вероятно, имеете 'thisRow', объявленный как' (NSUInteger *) '. Он должен быть объявлен простым «NSUInteger» и рассматриваться как таковой (во всех частях кода, где он используется). Также: вы уверены, что ваш массив заполнен перед вызовом функции replaceOBjectAtIndex:. Если индекс больше, чем число объектов в массиве 1, вы получите сообщение об ошибке. В ответ я добавил два заявления NSLog. Попробуйте и опубликуйте результаты. –

+0

@James: проблем нет. В этом случае либо 'self.tblView' неправильно ссылается (т. Е. Не указывает на' tblView'), либо self не является 'tableViewDelegate' или' tableViewDataSource'. Вы создаете «tableView» программно или с IB? Вы устанавливаете 'tblView.dataSource' и' tblView.delegate'? У вас есть '' в вашем .h-файле? –

Смежные вопросы