【问题标题】:iOS UITableView selection hides subview button background coloriOS UITableView 选择隐藏子视图按钮背景颜色
【发布时间】:2014-06-11 21:41:57
【问题描述】:

我有一个按钮作为表格视图单元格的子视图。 我希望表格视图在点击时显示选择,但选择颜色会覆盖按钮背景颜色。

例如,如果我有一个带有标题的红色背景按钮,那么标题将是唯一在选择时显示的内容,而不是颜色。颜色将仅显示为选择颜色。选择结束后,我可以再次看到该按钮,但有没有办法覆盖此行为?

【问题讨论】:

  • 您想在点击按钮时禁用更改按钮的选择?
  • 请给出代码,以便我们能够理解它是否出错了。
  • 没有什么“出错”。正如我所提到的,我希望单元格显示选择而不会使按钮颜色泛滥,这是所选单元格的子视图。不需要特定的代码。一旦你有一个彩色按钮作为任何表格单元格的子视图,你就会在任何地方看到它。

标签: ios objective-c uitableview selection


【解决方案1】:

试试这个:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CountryCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = nil;
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }  [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;

    // This is the code which solve the issue
    CAGradientLayer* gr = [CAGradientLayer layer];
    gr.frame = cell. frame;
    gr.colors = [NSArray arrayWithObjects:
                 (id)[[UIColor colorWithRed:0 green:0 blue:0 alpha:.0] CGColor]
                 ,(id)[[UIColor colorWithRed:0 green:0 blue:0 alpha:.0] CGColor]
                 , nil];
    gr.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:0],[NSNumber numberWithFloat:1],nil];
    [cell.layer insertSublayer:gr atIndex:0];

    // Put your button
    UIButton *btn = [[UIButton alloc] init];
    btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(10, 5, 100, 20);
    [btn setTitle:@"Testing" forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"headerimg.png"] forState:UIControlStateNormal];
    [cell.contentView addSubview:btn];

    return cell;
}

注意:您需要使用所需颜色的背景图片。不要在按钮中设置背景颜色。

它已经过测试和工作的解决方案。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2014-10-21
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 2018-09-03
    相关资源
    最近更新 更多