Search code examples
iosuitableviewuibutton

UIButton is not working in the header of my UITableView


I can't figure out why this UIButton is not working in the header of my UITableView. It's appearing there but the touch is not working.

The NSLog statement isn't triggering either. It's almost like it's beneath another view or something so that you can see it but the press action doesn't work.

thanks for any help with this

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

UIView *sectionHeader = [[UILabel alloc] initWithFrame:CGRectNull];
sectionHeader.backgroundColor = [UIColor clearColor];

[sectionHeader addSubview:self.topMapView];

// add map launch button
mapLaunchButton = [UIButton buttonWithType:UIButtonTypeCustom];
[mapLaunchButton addTarget:self
                    action:@selector(mapButtonTouch:)
          forControlEvents:UIControlEventTouchDown];
[mapLaunchButton setTitle:@"ggggggg" forState:UIControlStateNormal];
mapLaunchButton.frame = CGRectMake(0, 0, 300, 90);
mapLaunchButton.backgroundColor = [UIColor redColor];

[sectionHeader addSubview:mapLaunchButton];


  //  [sectionHeader bringSubviewToFront:mapLaunchButton];

    self.tableView.tableHeaderView = sectionHeader;

    return sectionHeader;

}
- (void)mapButtonTouch:(id)sender {

    NSLog(@"map button was touched");
}

Solution

  • I can see more than one mistake -

    1. If your table has only one section (to verify this check for numberOfSectionsInTableView delegate) then remove this line -

      self.tableView.tableHeaderView = sectionHeader;

    2. Set sectionHeader.frame to something appropriate (not CGRectNull). The benefit of setting section header (versus table header view) is that when user will scroll the table rows then the section header will stick on top (float) and will not go away. (Plain style table)

    3. Still the problem is not resolved, then please verify his method -

      -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 50; // depending upon the height of the sectionHeader }

    4. As pointed out by other poster, to capture touch event on UIButton UIControlEventTouchUpInside is preferred event.

    EDIT - (as table header view implementation)

    If you want to scroll it up then make it as table header (not section header). So remove all this from viewForHeaderInSection and put it inside viewDidLoad of your view controller class. Keep this line (don't remove it in this case) -

    self.tableView.tableHeaderView = sectionHeader;
    

    However, above points 2 and 4 still holds true.