我有一個UITableView,其中只能剔除4個單元格。如果我勾選了一定數量的單元格然後向上或向下滾動,它將隨機選擇單元格。我不明白這背後的邏輯,因爲我用於滴答的唯一方法是DidSelectRowAtIndex,它不會被執行(我在那裏放置一個斷點來檢查它)。我真的不知道這可能是造成這一點,但這裏是cellForRowAtIndex:當他們離開框架時,UITableView隨機剔除細胞
- (UITableViewCell *) tableView: (UITableView *) tableView
cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
static NSString *cellName = @"PrefsTableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
cellName];
if (cell == nil)
{
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellName] autorelease];
}
NSUInteger row = [indexPath row];
Drink *drink = [drinks objectAtIndex:row];
cell.textLabel.text = drink.name;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", drink.caffeine];
[[cell imageView] setImage:drink.image];
return cell;
}
我有一種感覺,它有事情做的,但我真的不能告訴。
這是它看起來像之前滾動到:
這是當我滾動到頂部會發生什麼:
我沒有點擊頂部一。如果我再次向下滾動,它可能會被取消,另一個會被打勾。
這可能是重要的,所以這裏是didSelectRowAtIndexPath方法方法:
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath: indexPath];
NSLog(@"TESTING");
if ((cell.accessoryType == UITableViewCellAccessoryNone) && [[DataContainerSingleton theDataContainerSingleton].favourites count] < 4)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[[DataContainerSingleton theDataContainerSingleton].favourites addObject:[drinks objectAtIndex:indexPath.row]];
NSLog(@"CHECKED %d", [[DataContainerSingleton theDataContainerSingleton].favourites count]);
}
else if (cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
for (int i = 0; i < [[DataContainerSingleton theDataContainerSingleton].favourites count]; i++)
{
NSString *drinkName = [[drinks objectAtIndex:indexPath.row] name];
NSString *favName = [[[DataContainerSingleton theDataContainerSingleton].favourites objectAtIndex:i] name];
if ([drinkName isEqualToString: favName])
{
cell.accessoryType = UITableViewCellAccessoryNone;
[[DataContainerSingleton theDataContainerSingleton].favourites removeObjectAtIndex:i];
NSLog(@"UNCHECKED %d", [[DataContainerSingleton theDataContainerSingleton].favourites count]);
}
}
}
}
你是否會動態改變你的tableview的內容?或者它只加載一次? – booleanBoy
它是動態更改的。每次向上或向下滾動新單元格進入屏幕時,cellForRowAtIndexPath會自動調用。 – JheeBz