2012-01-16 115 views
2

如下图所示,我在UITableViewCell中使用UIButton,可以选择此按钮,黄金星和未选中的灰色星。当选择UITableViewCell时,UIButton会被覆盖

enter image description here

的问题是,被选择的小区不断时,无论按钮被选中或未被它会变成灰色(这灰色颜色比中的未选定模式的灰度颜色不同星)。我一直在试图弄清楚为什么会发生这种情况,但没有运气。

enter image description here

这里是细胞的实施,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 

UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];  
UIButton *button = [[UIButton buttonWithType:UIButtonTypeCustom]retain]; 

//set the background of the cells 
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed: @"cellBackground.png"]]; 
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cellselected2.png"]]; 

// set the button content 
[button setImage:[UIImage imageNamed:@"star.png" ] forState:UIControlStateNormal]; 
[button setImage:[UIImage imageNamed:@"starSelected.png"] forState:UIControlStateSelected]; 
[button addTarget:self action:@selector(selectedButton:) forControlEvents:UIControlEventTouchUpInside]; 
[button setFrame:CGRectMake(280, 10, 24, 24)]; 

[cell addSubview:button]; 

return cell; 
} 

还当我点击该按钮时,电池选择按钮将完全消失!

谢谢,

回答

6

我想通了什么问题。问题是当选中单元格时,单元格中的UIButton将转到“高亮状态”。如果没有指定用于按钮按钮高亮显示状态的图像,它将看起来与我的情况相同。

于是我就加入了图像,我想是对的UIButton使用高亮状态,

[button setImage:[UIImage imageNamed:@"starSelected.png"] forState:UIControlStateHighlighted]; 

希望这有助于谁面临着同样的问题:)

+0

接受你自己的问题的答案没关系。 – 2012-01-22 05:52:18

1

您正在添加按钮到单元格框架,而不是它的contentView。

仅当选中单元格时,UITableViewCell才会将此属性的值作为子视图添加。它将选定的背景视图作为子视图直接添加到背景视图(backgroundView)的上方,如果它不是零,或者在所有其他视图之后。 虽然UITableViewCell将背景视图添加为所有其他视图背后的子视图,并使用其当前帧位置。

更换

[cell addSubview:favButton]; 

[cell.contentView addSubview:favButton]; 

,并应解决这个问题。

UITableViewCell对象的内容视图是单元格显示内容的默认超级视图。如果您想通过简单地添加附加视图来自定义单元格,则应该将它们添加到内容视图中,以便在单元格进入和退出编辑模式时适当定位它们。

这一切都在AppleDocs ^^

编号:http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UITableViewCell_Class/Reference/Reference.html

+0

不幸的是,这并没有解决它 – Mona 2012-01-16 09:26:31

+1

@Mona如果你添加[cell bringSubviewToFront:button];选择后。或cell [cell sendSubviewToBack:cell.selectedBackground]; ? – 2012-01-16 09:33:14

+0

没有工作。尽管如此,感谢 – Mona 2012-01-18 04:08:39

1

你其他人修好了当然可以设置突出显示状态的图像。另一种选择是,如果要为UIControlStateNormalUIControlStateHighlighted使用相同的图像,也可以说 button.adjustsImageWhenHighlighted = NO,默认值为YES

+0

这不适合我。我没有图像(只是背景颜色),当单元格被选中时,按钮也被选中。我也将这些按钮添加到contentView – Darren 2015-03-20 03:13:57