iOS UITableView 选择隐藏 subview 按钮背景色

标签 ios objective-c uitableview selection

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

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

最佳答案

试试这个:

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

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

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

希望对你有帮助。

关于iOS UITableView 选择隐藏 subview 按钮背景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23305590/

相关文章:

objective-c - 如何从 parse.com 检索图像

objective-c - react native 深度链接与 Facebook SDK 冲突

ios - 为什么我的 UITableViewCell 不取消选择并更新它的文本?

ios - 如何在 UITableView 中隐藏第一节标题(分组样式)

ios - 如何将cocos2d V3.3 添加到工作区并配置项目以在iOS 中使用cocos2D V3.3

ios - swift : Value Changing Control Events Not Calling?

ios - AVFoundation,如何关闭captureStillImageAsynchronouslyFromConnection时的快门声?

ios - 将 ImageView 连接到单元格声明时出错

ios - 使用异步数据更新 TableViewCell

iphone - 处理 Storyboard 中 View Controller 之间的模态转场