Перезагрузка таблицы не работает - PullRequest
2 голосов
/ 28 марта 2012

Обновил мой вопрос

У меня есть страница настроек, где я показываю название настройки слева, а также текущую настройку справа (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 я получаю предупреждение «Незавершенная реализация».Я понятия не имею, что могло бы означать это общее утверждение.Попытка поиска, и почти кажется, что это может означать что-либо.

Исправление

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

1 Ответ

2 голосов
/ 28 марта 2012

Две вещи: 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.

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

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

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

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

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

@interface YourClass:UIViewController <UITableViewDataSource>

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

self.tblView = thatTable;

add

self.tblView.dataSource = self;

И если вы используете любой из UITableViewDelegate методов, вы должны добавить это в микс:

@interface YourClass:UIViewController <UITableViewDataSource,UITableViewDelegate>

и

self.tblView.delegate = self;
...