我有一个按钮作为表格 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/