0

I am trying to add segmented control to tableviewheader. I am using the following code to do that

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"ALL", @"HOUSE", @"SENATE", nil]];
segmentedControl.frame = CGRectMake(24, 0, 272, 30);
[segmentedControl addTarget:self action:@selector(segmentedControlHasChangedValue:) forControlEvents:UIControlEventValueChanged];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;

segmentedControl.tintColor = [UIColor grayColor];    
[self.view addSubview:segmentedControl];
segmentedControl.selectedSegmentIndex = 0;

self.tableView.tableHeaderView = segmentedControl;

I can't set the frame, no matter what value is put its always 100% wide. How can i set the add 24px margin on left and right ?

Deepak ML
  • 79
  • 1
  • 13
  • Here you applying `UISegmentControl` to `UITableView` header thats why it take full width. You need to create `UIView` for header and than add segmentControl to this view. – Kampai Oct 20 '14 at 06:43

3 Answers3

1

That is because you are using the segment control as a tableHeaderView. a UITableViewHeaderView will be always be as wide as your tableView. You can only change the height.

akshaynhegde
  • 1,938
  • 3
  • 17
  • 36
1

First, you are adding segmentedControl on controller view [self.view addSubview:segmentedControl] and then assigning it to table header view

self.tableView.tableHeaderView = segmentedControl;

Which is wrong, you need to create a view with size table header size and then add segmentedControl add on view and assign this view to table header view.

Example

**UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"ALL", @"HOUSE", @"SENATE", nil]];
segmentedControl.frame = CGRectMake(24, 0, 272, 30);
[segmentedControl addTarget:self action:@selector(segmentedControlHasChangedValue:) forControlEvents:UIControlEventValueChanged];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.tintColor = [UIColor grayColor];    
[view addSubview:segmentedControl];
self.tableView.tableHeaderView = view;**
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
1

Adding to akshaynhegde answer, you can easily achieve this by adding an extra UIView as parent and add the UISegmentControl to that UIView. In this case the parent UIView will take the whole width of UITableView but not the UISegmentControl.

So following should be the change in your code

UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0,0,320.0,30.0)];
[view addSubview:segmentedControl];

self.tableView.tableHeaderView = view;

It should solve your problem.

Cheers.

iphonic
  • 12,615
  • 7
  • 60
  • 107