【问题标题】:UIButton gets covered when UITableViewCell is selected选择 UITableViewCell 时 UIButton 被覆盖
【发布时间】:2012-01-16 07:30:30
【问题描述】:

我在我的 UITableViewCell 中使用了一个 UIButton,这个按钮可以被选中,金色星形和未选中,灰色星形,如下图所示。

问题是,当单元格被选中时,无论按钮是否被选中,它都会变成灰色(这个灰色不同于星形未选中模式的灰色)。我一直试图弄清楚为什么会发生这种情况,但没有运气。

这里是单元格的实现,

- (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;
}

当我在选择单元格时点击按钮时,按钮也会完全消失!

谢谢,

【问题讨论】:

    标签: ios user-interface uitableview


    【解决方案1】:

    我想出了问题所在。问题是当单元格被选中时,单元格中的 UIButton 将进入它的“突出显示状态”。如果没有指定用于按钮的按钮突出显示状态的图像,它将看起来与我的情况相同。

    所以我只是通过添加我想在 UIButton 突出显示状态下使用的图像来修复它,

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

    希望这可以帮助面临同样问题的其他人:)

    【讨论】:

      【解决方案2】:

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

      UITableViewCell 仅在选择单元格时将此属性的值添加为子视图。如果它不是 nil 或在所有其他视图之后,它会将选定的背景视图作为子视图添加到背景视图 (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

      【讨论】:

      • @Mona 如果你添加 [cell bringSubviewToFront:button];选择后。或单元格 [cell sendSubviewToBack:cell.selectedBackground]; ?
      【解决方案3】:

      您当然可以将图像设置为突出显示状态。另一种选择,如果你想为UIControlStateNormal 和UIControlStateHighlighted 使用相同的图像,你也可以说 button.adjustsImageWhenHighlighted = NO,默认为YES。

      【讨论】:

      • 这对我不起作用。我没有图像(只是背景颜色),并且当单元格选择按钮也被选中。我也将按钮添加到 contentView
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 2019-05-30
      • 2020-02-10
      • 2015-12-26
      相关资源
      最近更新 更多