作者:博饼薄饼 | 来源:互联网 | 2024-12-20 10:24
在iOS开发中,自定义导航栏按钮是一个常见的需求。通常的做法是先创建一个标准的UIButton,然后将其转换为适合导航栏使用的UIBarButtonItem。
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"button_main.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(GotoSettings) forControlEvents:UIControlEventTouchUpInside];
button.frame = CGRectMake(x, y, x1, x2);
UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.rightBarButtOnItem= menuButton;
[button release];
[menuButton release];
如果需要在同一侧放置多个按钮,可以通过UISegmentedControl来实现这一功能,特别是在iOS 4.0及以下版本中。下面是一个使用分段控件(UISegmentedControl)的例子:
UISegmentedControl *segmentedCOntrol= [[UISegmentedControl alloc] initWithItems:@[@"开始", @"暂停"]];
[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
segmentedControl.frame = CGRectMake(0, 0, 80, 30);
segmentedControl.segmentedCOntrolStyle= UISegmentedControlStyleBar;
segmentedControl.momentary = YES;
segmentedControl.tintColor = [UIColor colorWithHue:0.6 saturation:0.33 brightness:0.69 alpha:0];
UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
self.navigationItem.rightBarButtOnItem= segmentBarItem;
为了响应用户的点击事件,我们需要在类中添加相应的处理方法:
- (void)segmentAction:(id)sender {
if ([sender selectedSegmentIndex] == 0) {
// 执行开始操作
} else if ([sender selectedSegmentIndex] == 1) {
// 执行暂停操作
}
}
从iOS 5.0开始,苹果提供了更加简便的方式来设置导航栏两侧的多个按钮,即使用setLeftBarButtonItems:animated:
和setRightBarButtonItems:animated:
方法。这使得开发者能够轻松地为导航栏添加多个功能按钮。
UIBarButtonItem *startBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(startDownloadAll)];
UIBarButtonItem *pauseBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:@selector(stopDownloadAll)];
[self.navigationItem setRightBarButtonItems:@[pauseBtn, startBtn]];