UISegmentedControl Within UIToolBar
Asked Answered
S

1

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.

Sam answered 23/6, 2011 at 20:34 Comment(1)
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.Incardination
Z
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];
Zyrian answered 23/6, 2011 at 20:46 Comment(6)
Isn't it necessary to wrap navSC in UIBarButtonItem?Wellgroomed
@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?Sam
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.Sam
@Faisal: You could add flexible space (UIBarButtonSystemItemFlexibleSpace) on either side of the segment.Zyrian
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?Sam
@Faisal: See above. Using flexible space pushes the middle item into the center.Zyrian

© 2022 - 2024 — McMap. All rights reserved.