本文主要是介绍调整导航条上leftBarButtonItem和rightBarButtonItem与屏幕边界的间距,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
我们发现,在设置navigationItem的leftBarButtonItem或rightBarButtonItem时,用CustomView初始化UIBarButtonItem,不论怎么设置CustomView的frame,添加到导航条上之后总是和屏幕边界有一定的间距(5pix),如何自由调整这个间距呢?
初始化一个用于控制间距的UIBarButtonItem实例negativeSpacer,并设置negativeSpacer的width属性的值,设为-5的时候,正好可以使按钮与屏幕边界值为0,以rightBarButtonItem情况为例
[plain] view plaincopy
- UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
- /**
- * 设置frame只能控制按钮的大小
- */
- btn.frame= CGRectMake(0, 0, 40, 44);
- [btn addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
- UIBarButtonItem *btn_right = [[UIBarButtonItem alloc] initWithCustomView:btn];
- UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
- initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
- target:nil action:nil];
- /**
- * width为负数时,相当于btn向右移动width数值个像素,由于按钮本身和边界间距为5pix,所以width设为-5时,间距正好调整
- * 为0;width为正数时,正好相反,相当于往左移动width数值个像素
- */
- negativeSpacer.width = -5;
- self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_right, nil];
- [btn_right release];
再看一个例子:
UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
btnBack.frame = CGRectMake(0, 0, 23, 23);
btnBack.backgroundColor = [UIColor clearColor];
[btnBack setImage:[UIImage imageNamed:@"bar_back_nomal.png"] forState:UIControlStateNormal];
[btnBack setImage:[UIImage imageNamed:@"bar_back_selected.png"] forState:UIControlStateHighlighted];
[btnBack setImage:[UIImage imageNamed:@"bar_back_selected.png"] forState:UIControlStateSelected];
[btnBack addTarget:self action:@selector(btnBackClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc]initWithCustomView:btnBack]];
UIButton * source = [UIButton buttonWithType:UIButtonTypeCustom];
source.frame = CGRectMake(0, 0, 35, 35);
source.backgroundColor = [UIColor clearColor];
[source setImage:[UIImage imageNamed:@"head_normal.png"] forState:UIControlStateNormal];
[source setImage:[UIImage imageNamed:@"head_press.png"] forState:UIControlStateHighlighted];
[source setImage:[UIImage imageNamed:@"head_press.png"] forState:UIControlStateSelected];
[source addTarget:self action:@selector(btnPublicNum:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem * btn_right = [[UIBarButtonItem alloc]initWithCustomView:source];
UIBarButtonItem * negativeSpacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
negativeSpacer.width = -6;
self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_right, nil];
OK:左右边界一模一样
这篇关于调整导航条上leftBarButtonItem和rightBarButtonItem与屏幕边界的间距的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!