这是我的代码
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *segmentTextContent = [NSArray arrayWithObjects:
NSLocalizedString(@"button1", @""),
NSLocalizedString(@"button2", @""),
NSLocalizedString(@"button3", @""), nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] nitWithItems:segmentTextContent];
segmentedControl.selectedSegmentIndex = 0;
segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.frame = CGRectMake(0, 0, 400, 30);
self.navigationItem.titleView = segmentedControl;
[segmentedControl release];
}
显示三个按钮,但我不知道如何在按钮中设置动作,请提前感谢
答案 0 :(得分:3)
在segmentedControl创建时添加目标,如下所示
[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
在那个选择器中
-(IBAction) segmentAction:(id)sender{
UISegmentedControl *segmentedControl = (UISegmentedControl *)sender;
NSLog(@"Segment clicked: %d", segmentedControl.selectedSegmentIndex);
switch (segmentedControl.selectedSegmentIndex) {
case 0:
self.segmentLabel.text =@"Segment 1 selected.";
break;
case 1:
self.segmentLabel.text =@"Segment 2 selected.";
break;
default:
break;
}
答案 1 :(得分:1)
你必须制作3个按钮并将它们添加到UIToolbar。
- (void)viewDidLoad
{
[super viewDidLoad];
// create a toolbar to have the buttons at the right side of the navigationBar
UIToolbar* toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 150, 44.01)];
toolbar.tintColor = [UIColor clearColor];
[toolbar setTranslucent:YES];
// create the array to hold the buttons, which then gets added to the toolbar
NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:3];
// Create button1
UIBarButtonItem *button1 = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(button1Pressed)];
[buttons addObject:button1];
[button1 release];
// Create button2
UIBarButtonItem *button2 = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(button2Pressed)];
[buttons addObject:button2];
[button2 release];
// Create button3
UIBarButtonItem *button3 = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self action:@selector(button3Pressed)];
[buttons addObject:button3];
[button3 release];
// stick the buttons in the toolbar
[toolbar setItems:buttons animated:NO];
//self.toolbarItems = buttons;
[buttons release];
// and put the toolbar in the nav bar
[[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithCustomView:toolbar] autorelease]];
[toolbar release];
}
...
- (void)button1Pressed
{
//do stuff
}
- (void)button2Pressed
{
//do stuff
}
- (void)button3Pressed
{
//do stuff
}