我有一个按钮作为表格视图单元格的子视图。 我希望表格视图在点击时显示选择,但选择颜色会覆盖按钮背景颜色。
例如,如果我有一个带标题的红色背景按钮,则标题将是选择时唯一显示的内容,而不是颜色。颜色将仅显示为选择颜色。当选择结束时,我可以再次看到该按钮,但有没有办法覆盖此行为?
答案 0 :(得分: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;
}
注意:您需要使用所需颜色的背景图像。不要在按钮中设置背景颜色。
已经过测试过&工作解决方案。
希望它能帮到你。