2016-02-22 124 views
1

我想在每個視圖中點擊時更改點擊UITableViewHeader。我寫了下面的代碼,但它根本不起作用。請幫助如何解決這個問題。如何在iOS中點擊時更改UITableViewHeader背景顏色

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 

    view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 25)]; 
    label = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, tableView.frame.size.width, 25)]; 
    [label setFont:CHECKOUT_HEADER_FONT]; 
    label.textColor = GLOBAL_PRIMARY_COLOR; 
    label.textAlignment = NSTextAlignmentLeft; 
    [label setText:CategoryName]; 
    label.backgroundColor = GLOBAL_BACKGROUND; 
    [view setBackgroundColor: GLOBAL_BACKGROUND]; 
    [view addSubview:label]; 

    view.tag = section; 
    UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionHeaderTapped:)]; 
    [view addGestureRecognizer:headerTapped]; 

    return view; 
} 


- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer{ 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag]; 

    // DOES NOT WORK 
    UIView *header = [_productTableView headerViewForSection:indexPath.section]; 
    header.backgroundColor = GLOBAL_PRIMARY_COLOR; 
} 
+0

您可以使用一個按鈕,而不是標籤,並刪除輕敲手勢。 –

+0

爲什麼要使用按鈕? – ppshein

+0

如果你只想改變背景顏色,那麼按鈕是最好的,否則在視圖的巨大變化,你可以去點擊手勢。但我懷疑,輕拍手勢只能在標題上工作,它可以作爲一個整體在tableview上工作,在這種情況下,didSelect委託函數將不會被調用。 –

回答

1

您可以使用此viewForHeaderInSection

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
    UIView *tempView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 25)]; 
    tempView.backgroundColor=[UIColor blueColor]; 

    tempView.tag = section; 
    UITapGestureRecognizer *headerTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionHeaderTapped:)]; 
    [tempView addGestureRecognizer:headerTapped]; 

    return tempView; 
} 
- (IBAction)sectionHeaderTapped:(UITapGestureRecognizer *)recognizer 
{ 
    switch (recognizer.view.tag) { 
     case 0: 
      recognizer.view.backgroundColor = [UIColor redColor]; 
      break; 

     default: 
      break; 
    } 
} 
相關問題