7

I know how to add a UISegmentedControl to a UIToolBar from within IB, but I am trying to do the same programmatically, because I am using a custom subclass of UISegmentedControl with doesn't have an XIB.

This is the code for the UISegmentedControl:

SVSegmentedControl *navSC = [[SVSegmentedControl alloc] initWithSectionTitles:[NSArray arrayWithObjects:@"List", @"Calendar", nil]];
navSC.delegate = self;
[self.view addSubview:navSC];
[navSC release];
navSC.center = CGPointMake(160, 70);

I was thinking of doing something like [self.toolbar addSubview:navSC], but that didn't show anything.

tipycalFlow
  • 7,594
  • 4
  • 34
  • 45
  • Note that you *can* create a regular UISegmentedControl in IB, then change its class to your custom subclass. Any properties specific to your subclass you'll have to set up in a method like `awakeFromNib`. – benzado Jun 24 '11 at 16:24

1 Answers1

14

You need to use the UIToolbar method – setItems:animated: (detailed in the documentation):

UIBarButtonItem *segItem = [[UIBarButtonItem alloc] initWithCustomView:navSC];
UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL];
[toolBar setItems:[NSArray arrayWithObjects:spaceItem,segItem,spaceItem,nil] animated:YES];
[segItem release];
[spaceItem release];
PengOne
  • 48,188
  • 17
  • 130
  • 149
  • 1
    Isn't it necessary to wrap `navSC` in `UIBarButtonItem`? – ZhangChn Jun 23 '11 at 21:11
  • @ZhangChn, I think you are right about wrapping it in a `UIBarButtonItem` first because right now, it is crashing the app. Can you show me how? –  Jun 23 '11 at 21:52
  • Thanks that worked perfectly. But do you know how I can center the button? Right now it is showing on the left side of the toolbar. –  Jun 23 '11 at 22:03
  • @Faisal: You could add flexible space (`UIBarButtonSystemItemFlexibleSpace`) on either side of the segment. – PengOne Jun 23 '11 at 22:07
  • Ok I added this: ` UIBarButtonItem *fixedItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:NULL] autorelease];, but how do I add it to toolbar along with the `segItem`? –  Jun 23 '11 at 22:12
  • @Faisal: See above. Using flexible space pushes the middle item into the center. – PengOne Jun 23 '11 at 22:18