我正在尝试在表格视图的每个单元格中创建一个“blank_star 图标”,用户单击它后,该星应该变成一个“实心”星。
我创建了一个子类,UIButton
如下所示
//.h file
@interface Bleh : UIButton {
}
+(id)specialInit;
-(void)vvv;
@end
//.m file
@implementation Bleh
+(id) specialInit
{
Bleh* button=[super buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"blank_star.png"] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"star.png"] forState:UIControlStateDisabled];
[button addTarget:button action:@selector(vvv) forControlEvents:UIControlEventTouchUpInside];
NSLog(@"%d",[button isEnabled]);
return button;
}
-(void)vvv
{
NSLog(@"button tapped");
[self setEnabled:false];
}
@end
我在表格视图的cellforRow:
方法中添加了 UIButton 的子类,如下所示:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
int row = indexPath.row;
NSString *cc = [array objectAtIndex:row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// Configure the cell...
Bleh *button = [Bleh specialInit];
button.frame = CGRectMake(0, 0, 100, 100);
NSLog(@"Button:%@ at row number: %i",button, indexPath.row);
cell.textLabel.text = cc;
[cell.contentView addSubview:button];
}
return cell;
}
但是我在运行应用程序时遇到了问题。例如,如果我单击标记为“a”的单元格,星形将按预期变为实心。
奇怪的是,向下滚动后,我还看到其他一些带有实心星的单元格(参见单元格'e')。
任何人都可以帮助解释为什么会这样吗?似乎state
该单元格的 正在被其他单元格重新使用。我怎样才能避免这种情况发生?