2014-04-26 82 views
3

我有一個按鈕作爲表視圖單元格的子視圖。 我希望表格視圖在點擊時顯示選擇,但選擇顏色會覆蓋按鈕背景顏色。iOS UITableView選擇隱藏子視圖按鈕背景顏色

例如,如果我有一個帶有標題的紅色背景按鈕,標題將是選擇時顯示的唯一標題,而不是顏色。顏色將只顯示爲選擇顏色。選擇結束後,我可以再次看到該按鈕,但有什麼方法可以覆蓋此行爲?

+0

你想禁止改變按鈕的選擇,當它點擊? –

+0

請提供代碼,以便我們能夠理解它是否出錯。 – Javid

+0

沒有什麼是「出錯」。正如我所提到的,我希望單元格顯示選擇而不會溢出按鈕顏色,這是所選單元格的子視圖。不需要特定的代碼。一旦您將彩色按鈕作爲任何表格單元格的子視圖,您就會在任何地方看到它。 – BridgeTheGap

回答

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

注:你需要用你想要的顏色的背景圖像。不要在背景顏色中設置按鈕。

其已經測試&工作解決方案。

希望它能幫助你。