我有一個奇怪的問題,我的UITableView
...我添加一個UIButton
作爲子視圖到每個單元格,但是當任何一個單元格離開視圖發生了什麼事情,當我再次向上滾動,我可以看到UIButton
某些單元格的背景圖片重疊!UITableViewCell和圖像重疊
的cellForRowAtIndexPath
方法我使用包含下面的代碼,這將增加該UIButton
實例
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:@"MyCell"];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
UIFont *titleFont = [UIFont fontWithName:@"Arial-BoldMT" size:14.0];
[[cell textLabel] setFont:titleFont];
[cell autorelease];
}
if([cell viewWithTag:indexPath.row]==nil){
UIButton *buttonLeft = [UIButton buttonWithType:UIButtonTypeCustom];
buttonLeft.tag=indexPath.row;
if ([[myArray objectAtIndex:indexPath.row] isEqualToString:@"item1"]) {
[buttonLeft addTarget:self action:@selector(doThat:) forControlEvents:UIControlEventTouchUpInside];
[buttonLeft setBackgroundImage:[UIImage imageNamed:@"item1.png"] forState:UIControlStateNormal];
[buttonLeft setFrame: CGRectMake(5.0f, 6.2f, 30.0f, 30.0f)];
}else{
[buttonLeft addTarget:self action:@selector(doThat:) forControlEvents:UIControlEventTouchUpInside];
[buttonLeft setBackgroundImage:[UIImage imageNamed:@"item2.png"] forState:UIControlStateNormal];
[buttonLeft setFrame: CGRectMake(5.0f, 6.2f, 30.0f, 30.0f)];
}
[cell addSubview:buttonLeft];
}
cell.textLabel.text=[NSString stringWithFormat:@" %@",[myArray objectAtIndex:indexPath.row]];
return cell;
}
顯然,此代碼爲某種原因添加的UIButton顯示每次所述細胞。我希望每個按鈕子視圖只能添加一次.. 我在做什麼錯了?
非常感謝您的幫助
也看到這個問題:http://stackoverflow.com/questions/1802707/detecting-which-uibutton-was-pressed-in-a-uitableview – Vladimir 2010-09-16 15:22:45