2012-06-02 77 views
3

我知道,一個「表視圖頭」(表視圖的最頂級的一部分)是一個查看 所以我嘗試將UITapGestureRecognizer添加到它,但它不工作...將手勢識別器添加到tableView標頭不起作用?

代碼很簡單:

- (void)tap:(UITapGestureRecognizer *)recognizer 
{ 
    // do something 
} 

UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)]; 
[self.tableView.tableHeaderView addGestureRecognizer:recognizer]; 

這裏的任何提示要小心嗎?非常感謝

+1

你在哪兒打電話給這段代碼? –

+0

您是否在init或viewDidLoad或其他地方調用它? –

回答

4

下面是對我的作品的東西: 而是添加此:

self.tableView.tableHeaderView 

我上實現代碼如下每個的UILabel添加手勢識別。

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

    UILabel *headerLabel = [[UILabel alloc]init]; 
    headerLabel.tag = section; 
    headerLabel.userInteractionEnabled = YES; 
    headerLabel.backgroundColor = [UIColor greenColor]; 
    headerLabel.text = [NSString stringWithFormat:@"Header No.%d",section]; 
    headerLabel.frame = CGRectMake(0, 0, tableView.tableHeaderView.frame.size.width, tableView.tableHeaderView.frame.size.height); 


    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(catchHeaderGesture:)]; 
    tapGesture.cancelsTouchesInView = NO; 
    [headerLabel addGestureRecognizer:tapGesture]; 

    return headerLabel; 

    //return nil; 
} 

-(void)catchHeaderGesture:(UIGestureRecognizer*)sender 
{ 
    UILabel *caughtLabel = (UILabel*)sender.view; 

    NSLog(@"header no : %d", caughtLabel.tag); 
} 

我希望有幫助。

+0

'tableView.tableHeaderView'與'viewForHeaderInSection'不一樣:' –

+0

只要你使用'obj.userInteractionEnabled = YES',那麼它就可以工作。我用'tableView.tableHeaderView'來使用它 –

2

所有 首先請確保您調用viewDidLoad中或該代碼段viewWillAppear中

UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)]; 
[self.tableView.tableHeaderView addGestureRecognizer:recognizer]; 

其次,請確保

self.tableView.tableHeaderView 

不爲空,加

NSLog([self.tableView.tableHeaderView description]); 

並檢查控制檯的輸出

我只是想你的代碼和絲錐收到正確

+2

謝謝,我的tableView頭部視圖是一個「UILabel」。我添加了「NSLog([self.tableView.tableHeaderView description]);」到我的代碼,它不工作仍然....但我發現,在控制檯中,有一些像「userInteractionEnabled = NO」。然後我將一行代碼添加到該標籤:「label.userInteractionEnabled = YES」,最後它可以工作!你知道原因嗎? :-) – joshz

+2

@joshz:這是因爲UILabel上的用戶交互默認是禁用的。 – user523234

+0

對於uiimageview也是如此 – baskInEminence