在设置navigationItem的leftBarButtonItem或rightBarButtonItem时,
用CustomView初始化UIBarButtonItem,不论怎么设置CustomView的frame,
添加到导航条上之后总是和屏幕边界有一定的间距(5pix),
如何自由调整这个间距呢?
下面介绍两种方法:
1、不用直接设置rightBartButtonItem而是设置rightBartButtonItems,并且第一个item设置为一个占位。
- - (UIButton *)addRightItemWithTitle:(NSString *)title action:(SEL)action {
- UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
- CGSize size = [title sizeWithFont:[UIFont systemFontOfSize:16]];
-
-
- button.frame = CGRectMake(0, 0, size.width <= 10 ? 70 : size.width + 10, 44);
- button.titleLabel.textColor = [UIColor whiteColor];
- button.titleLabel.font = [UIFont systemFontOfSize:16];
- button.titleLabel.textAlignment = NSTextAlignmentRight;
- [button setTitle:title forState:UIControlStateNormal];
-
-
-
-
- UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
- initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
- target:nil action:nil];
- negativeSpacer.width = -15;
-
- [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
- UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:button];
- self.navigationItem.rightBarButtonItems = @[negativeSpacer, backItem];
- return button;
- }
2、如果是只有图片,那么通过设置
[button setImageEdgeInsets:UIEdgeInsetsMake(0, -15, 0, -15)];这样也可以调整
- - (UIButton *)addRightItemWithImage:(NSString *)imageName action:(SEL)action {
- UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
- UIImage *image = [UIImage imageNamed:imageName];
- button.frame = CGRectMake(0, 0, image.size.width, image.size.height);
-
-
-
- [button setImageEdgeInsets:UIEdgeInsetsMake(0, 15, 0, -15)];
-
- [button setImage:image forState:UIControlStateNormal];
- [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
- button.titleLabel.font = [UIFont systemFontOfSize:16];
- UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:button];
- self.navigationItem.rightBarButtonItem = rightItem;
- return button;
- }