テーブルビューのすべてのセルに「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
セルのが他のセルで再利用されているようです。どうすればこれを回避できますか?