Is it possible to add UIBarButtonItem to a Segmented Control
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];
UISegmentedControl
inherits from UIControl
which inherits from UIView
, so you can add subViews to it as you would to a UIView.
However, the segmented aspect is quite different. Each segment has an image
property and title
property, but that's all.
When you invoke initWithItems:
, this must be an NSArray
of UIImages
or NSStrings
.
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 title
and image
properties of the UISegmentedController
and the customize the action in whatever method the controller is meant to trigger. For example:
-(void)segmentAction:(UISegmentedController *)segment {
if (segment.selectedSegmentIndex == 0) {
[self atol];
} else {
[self ltoz];
}
}
I have no idea what you cannot accomplish this way that you wish to do.
精彩评论