初始化toolbar的代码
- (void)initToolBar
{
// UIBarButtonItem * flexble = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
_showSegment = [[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"开始",@"停止", nil]];
[_showSegment addTarget:self action:@selector(showsSegmentAction:) forControlEvents:UIControlEventValueChanged];
_showSegment.selectedSegmentIndex = 1;
UIBarButtonItem * showItem = [[UIBarButtonItem alloc]initWithCustomView:_showSegment];
//退出程序按钮
UIButton * myBtn = [UIButton buttonWithType:UIButtonTypeSystem];
[myBtn setFrame:CGRectMake(0, 0, 80, 44)];
myBtn.titleLabel.font=[UIFont systemFontOfSize:15];
[myBtn setTitle:@"退出程序" forState:UIControlStateNormal];
myBtn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
[myBtn addTarget:self action:@selector(exitAPP) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *myButtonItem1 = [[UIBarButtonItem alloc]initWithCustomView:myBtn];
NSLog(@"showitem width = %f totalwidth = %f",_showSegment.frame.size.width,CGRectGetWidth(self.view.bounds));
_DesLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds)- _showSegment.frame.size.width-26-80, 40)];
_DesLabel.font=[UIFont systemFontOfSize:15];
_DesLabel.backgroundColor = [UIColor clearColor];
_DesLabel.textAlignment = NSTextAlignmentCenter ;
UIBarButtonItem * myButtonItem2 = [[UIBarButtonItem alloc]initWithCustomView:_DesLabel];
self.toolbarItems = [NSArray arrayWithObjects:showItem,myButtonItem2,myButtonItem1, nil];
}
退出程序的代码
//退出App
- (void)exitAPP
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"要退出程序吗" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
exit(0);
}];
[alertController addAction:cancelAction];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
}
Navigation bar 添加搜索栏和右边的按钮
搜索栏:
#pragma mark初始化 搜索栏
- (void)initSearchBar
{
_searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
_searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
_searchBar.barStyle = UIBarStyleBlack;
_searchBar.delegate = self;
_searchBar.placeholder = @"请输入要搜索的地址";
_searchBar.keyboardType = UIKeyboardTypeDefault;
//添加搜索栏到NavigationItem的titleView上面
self.navigationItem.titleView = self.searchBar;
[self.searchBar sizeToFit];
}
右边离线地图按钮(action还没写)
- (void)addOfflineButton
{
//创建一个button
UIBarButtonItem * rightButton = [[UIBarButtonItem alloc]initWithTitle:@"离线地图" style:UIBarButtonItemStylePlain target:self action:nil];
self.navigationItem.rightBarButtonItem = rightButton;
}
显示效果如下: