Question

I have a button as a subview of a table view cell. I want the table view to show selection when tapped, but the selection color overrides the button background color.

For example, if I have a red background button with a title, the title will be the only thing showing upon selection, not the color. The color will just appear as the selection color. When selection is over, I can see the button again, but is there any way to override this behavior?

Était-ce utile?

La solution

Try this :

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

Note: You need to use the Background image of the color you want. Don't set the Background colour in button.

Its already tested & working solution.

Hope it'll help you.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top