私の UITableViewCells には、accessoryView として UIButton があります。ではcellForRowAtIndexPath
、ブロックを使用してバックグラウンドでサーバーからデータをフェッチします。ブロックが呼び出されると、selected
取得したデータに応じてセル内のボタンのプロパティを設定します。
ユーザーが TableView をすばやく上下にスクロールすると、一部のボタンの状態が正しく設定されないことがあります。これは、間違った UITableViewCell がブロック内で使用されているためだと思います (実際のセルではなく、再利用されたセルであり、おそらくオフスクリーンになっています)。
ブロック内のセルが目的のセルであることを確認するにはどうすればよいですか?
重要な部分を含むコードの簡略版を次に示します。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//FoundUserCell is a subclass of UITableViewCell
FoundUserCell *cell = [tableView dequeueReusableCellWithIdentifier:[self cellIdentifierTableView:tableView]];
//set the textLabel (this works already)
cell.textLabel = @"something";
//fetch info from the DB that I need to state the state of the button
//theButton is a property of FoundUserCell
//theButton is always set to a FoundUserCell's accessoryView
[self fetchInBackgroundWithBlock:^(int buttonState) {
//I think that, at this point, cell is sometimes no longer the cell I want
if(buttonState == 0)
cell.theButton.selected = NO;
else
cell.theButton.selected = YES;
//WHAT CAN I DO INSIDE THIS BLOCK TO MAKE SURE THAT THE CELL I'M SETTING IS THE CELL I WANT?
}];
return cell;
}
基本的に、セルが正しいセルでない場合、ブロック内のボタンの状態を設定したくありません。