在日常的开发过程中经常要根据设计图来调整导航栏的样式,在默认情况下,导航栏返回按钮长这个样子
替换返回按钮非常简单,只需要在ViewController中创建一个UIBarButtonItem和一张图片,并为按钮添加相应的点击事件即可,代码如下
- (void)viewDidLoad {
[superviewDidLoad];
UIButton* leftBtn = [UIButtonbuttonWithType:UIButtonTypeSystem];
leftBtn.frame =CGRectMake(0,0,25,25);
[leftBtn setBackgroundImage:[UIImageimageNamed:@"back"] forState:UIControlStateNormal];
[leftBtn addTarget:selfaction:@selector(leftBarBtnClicked:) forControlEvents:UIControlEventTouchUpInside];self.navigationItem.leftBarButtonItem = [[UIBarButtonItemalloc]initWithCustomView:leftBtn];
}
- (void)leftBarBtnClicked:(UIButton*)btn{
[self.navigationController popViewControllerAnimated:YES];
}
效果如下
往往需要调整一下返回按钮的位置,左侧导航栏一般希望往左侧调整一下,而右侧导航栏按钮希望尽量靠右侧,这种情况如何处理呢?修改UIButton的frame,能不能解决这个问题,答案是不能。熟悉OC原生API的同学应该知道,苹果提供的UIButtonBarItem中有个叫做UIBarButtonSystemItemFixedSpace的控件,利用它,我们就可以轻松调整返回按钮的位置。具体使用方法如下
UIButton* leftBtn = [UIButtonbuttonWithType:UIButtonTypeSystem];
leftBtn.frame =CGRectMake(0,0,25,25);
[leftBtn setBackgroundImage:[UIImageimageNamed:@"back"] forState:UIControlStateNormal];
[leftBtn addTarget:selfaction:@selector(leftBarBtnClicked:) forControlEvents:UIControlEventTouchUpInside];UIBarButtonItem* leftBarBtn = [[UIBarButtonItemalloc]initWithCustomView:leftBtn];
UIBarButtonSystemItemFixedSpaceUIBarButtonItem* spaceItem = [[UIBarButtonItemalloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpacetarget:nilaction:nil];
//将宽度设为负值 负值往左 正值往右
spaceItem.width =-15;
//将两个BarButtonItem都返回给NavigationItem
self.navigationItem.leftBarButtonItems = @[spaceItem,leftBarBtn];
效果如下
网友评论