I want to know if it is possible to add UIBarButtons to a SegmentedControl. It compiles but gives a runtime error:
-[UIBarButtonItem isEqualToString:]: unrecognized selector sent to instance 0x4b4fcc0
Here is my code.
UIBarButtonItem *atolButton = [[UIBarButtonItem alloc] initWithTitle:@"A to L"
style:UIBarButtonItemStyleBordered target:self action:@selector(atol:)];
UIBarButtonItem *ltozButton = [[UIBarButtonItem alloc] initWithTitle:@"L to Z"
style:UIBarButtonItemStyleBordered target:self action:@selector(ltoz:)];
NSArray *titleButtons = [NSArray arrayWithObjects: atolButton, ltozButton, nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:titleButtons];
self.navigationItem.titleView = segmentedControl;
[segmentedControl release];
...
- (void)atol:(id) sender {
NSLog(@"atol called");
}
- (void)ltoz:(id) sender {
NSLog(@"ltoz called");
}
I have been able to make it work with the following code
NSArray *itemArray = [NSArray arrayWithObjects: @"a to l", @"l to z", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
segmentedControl.selectedSegmentIndex = 1;
[segmentedControl addTarget:self action:@selector(atol:)
forControlEvents:UIControlEventValueChanged];
self.navigationItem.titleView = segmentedControl;
[segmentedControl release];
UISegmentedControlinherits fromUIControlwhich inherits fromUIView, so you can add subViews to it as you would to a UIView.However, the segmented aspect is quite different. Each segment has an
imageproperty andtitleproperty, but that’s all.When you invoke
initWithItems:, this must be anNSArrayofUIImagesorNSStrings.I have no idea what you’re trying to do that compels you to add buttons to a segmented controller, but I encourage you instead to set the
titleandimageproperties of theUISegmentedControllerand the customize the action in whatever method the controller is meant to trigger. For example:I have no idea what you cannot accomplish this way that you wish to do.