Problem when inserting a segmented control into a header view

I am trying to add UISegmentedControl to my tableview. I have two sections in my table view and I want the segmented control to be placed in the second section. In my implementation, I am overriding viewForHeaderInSection as follows.

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

if (section == 1)
{   
    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(10, 0,tableView.bounds.size.width, 10)] autorelease];
    NSArray *segmentTextContent = [NSArray arrayWithObjects:NSLocalizedString(@"Singles", @""), NSLocalizedString(@"Everyone", @""),nil];
    UISegmentedControl *segmentedControl = [[[UISegmentedControl alloc] initWithItems:segmentTextContent] autorelease];
    segmentedControl.selectedSegmentIndex = 1;
    segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    segmentedControl.frame = CGRectMake(0, 0, tableView.bounds.size.width+10, 20);
    [segmentedControl addTarget:self action:@selector(loadTable:) forControlEvents:UIControlEventValueChanged];
    [headerView addSubview:segmentedControl]; 
    return headerView;
}
else
{
    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(10, 0,tableView.bounds.size.width, 10)] autorelease];
    return headerView;
}

      

}

My problem is that once I select a specific segment, it will not be selected. that is, it does not turn dark as expected. I placed the segmented control in my navbar before and it will color the segment after selection as expected.

Any help would be much appreciated. Thanks to

+2


a source to share


2 answers


This is a late reaction, but I ran into the same issue and figured out the problem. In the above code, the headerView is recreated every time the tableView calls reloadData (which in my case happens after I have resorted to the data based on a click on the sharded controller) and so the sharded control returns to its original state, and the finishing touches by - apparently not a reflection.

To solve this problem, I made a segmentedControl ivar and checked if it exists. If so then just call

[headerView addSubview: segmentedControl];

      



otherwise, do all the customization of the control.

Hope it helps.

+1


a source


Have you ever found the answer to this question? I implemented pretty much the same thing and it worked fine. I assume that you have determined that you have more control over the scope.

CGRectMake(0, 0, tableView.bounds.size.width+10, 20)

      



I believe this will result in the control not receiving touch events in all cases.

0


a source







All Articles