Почему мой UITableViewCell не отменяет выбор и не обновляет его текст? - PullRequest
2 голосов
/ 04 января 2011

У меня есть UITableView со списком историй и ячейкой внизу, которая загружает больше историй. Я пытаюсь отменить выбор ячейки «Больше историй ...» и изменить ее текст на «Загрузка ...» при нажатии. Я искал по всему Интернету и по всему стеку, и я не могу понять, почему мой код работает неправильно. Прямо сейчас, когда ячейка «More Stories ...» нажата, она остается выделенной и никогда не меняет свой текст.

Для тех, кто спрашивает, moreStories добавляет 25 новых историй внизу таблицы.

Оригинальный код:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
if (storyIndex == [stories count]) {
    UITableViewCell *moreCell = [tableView dequeueReusableCellWithIdentifier:@"more"];
    if (moreCell == nil) {
        moreCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"more"] autorelease];
    } // Set up the cell
    moreCell.textLabel.text = @"Loading...";

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self moreStories];
} else { 
    NSLog(@"%@",[[stories objectAtIndex: storyIndex] objectForKey: @"link"]);
    webViewController *webController;
    webController = [[webViewController alloc] initWithURLPassed:[[stories objectAtIndex: storyIndex] objectForKey: @"link"]];
    [self.navigationController pushViewController:webController animated:YES];
    [webController release];
    webController =nil;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:nil action:nil];
}
}

Обновлено , но все еще не работает правильно. Теперь он, наконец, отменяет выбор ячейки и меняет текст на «Загрузка ...», но только после того, как moreStories завершит загрузку всех историй. Очевидно, я хочу, чтобы текст загружался, пока загружаются истории. 1/4/10 ~ 9 вечера

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
if (storyIndex == [stories count]) {
    UITableViewCell *moreCell = [tableView cellForRowAtIndexPath:indexPath];
    moreCell.textLabel.text = @"Loading...";
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSArray *arr = [[NSArray alloc] initWithObjects:indexPath,nil];
    [tableView beginUpdates];
    [tableView reloadRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationFade];
    [tableView endUpdates];
    [self moreStories];
} else { 
    NSLog(@"%@",[[stories objectAtIndex: storyIndex] objectForKey: @"link"]);
    webViewController *webController;
    webController = [[webViewController alloc] initWithURLPassed:[[stories objectAtIndex: storyIndex] objectForKey: @"link"]];
    [self.navigationController pushViewController:webController animated:YES];
    [webController release];
    webController =nil;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:nil action:nil];
}
}

Ответы [ 2 ]

2 голосов
/ 04 января 2011

[tableView dequeueReusableCellWithIdentifier:@"more"] говорит табличному представлению дать вам другую ячейку, которая находится в очереди на повторное использование и вне того, что отображается. Более того, условие moreCell == nil создает новую совершенно новую ячейку , когда для удаления из очереди не было доступной повторно используемой ячейки. Этот шаблон предназначен только для использования источником данных табличного представления при создании ячеек таблицы для отображения.

Вам нужно использовать [tableView cellForRowAtIndexPath:indexPath] вместо того, чтобы получить ячейку, которая была фактически выбрана.

UITableViewCell *moreCell = [tableView cellForRowAtIndexPath:indexPath];
moreCell.textLabel.text = @"Loading...";

РЕДАКТИРОВАТЬ: на основе вашего обновления это выглядит так, как aBitObvious говорит в комментариях, запрос загрузки URL блокирует обновление пользовательского интерфейса. Когда вы обновляете свой пользовательский интерфейс, попробуйте запустить новый поток и загрузить данные в этом потоке, чтобы ваш пользовательский интерфейс мог обновляться без помех.

0 голосов
/ 04 января 2011

Я пошел вперед и сделал очень простую версию того, чего вы пытаетесь достичь.Посмотрите, поможет ли это вообще.То, как я это сделал, состояло в том, что я пошел дальше и изменил источник данных UITableView.Что в конечном итоге вы можете делать, чтобы загрузить больше историй.Главное, что нужно помнить, если вы изменяете источник данных, вам необходимо перезагрузить tableView.

- (void)viewDidLoad {

  NSArray *array = [[NSArray alloc] initWithObjects:@"Story 1", @"Story 2", @"Story 3", @"Story 4", @"Story 5", @"More Stories", nil];
  self.stories = array;
  [array release];

  [super viewDidLoad];
}

// TableView DataSource Methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
 {
   return [stories count];
 }

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  static NSString *CellIdentifier = @"CellIdentifier";
  UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:CellIdentifier]; 
  if (cell == nil) {
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: CellIdentifier] autorelease];
  }

  cell.textLabel.text = [stories objectAtIndex:[indexPath row]];
  return cell;
 }

// TableView Делегаты

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

if ([indexPath row] == [stories count] - 1) {
    //Get more stories
    [table deselectRowAtIndexPath:indexPath animated:YES];

    NSArray *array = [[NSArray alloc] initWithObjects:@"Story 1*", @"Story 2*", @"Story 3*", @"Story 4*", @"Story 5*", @"Loading...", nil];
    self.stories = array;
    [array release];

    NSArray *arr = [[NSArray alloc] initWithObjects:indexPath,nil];

    [table beginUpdates];
    [table reloadRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationFade];
    [table endUpdates];
}
else {
    //Call your methods to load the stories.
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...