前言:开发中常有在导航栏添加图标的需求,可以直接用系统自定义的,但有时候希望图标在自己想要的位置出现,但系统自定义的按钮位置是固定的 所以我参照网上的资料 再通过自己的实践总结得出下面的两个方法:
刚开始没设置位置的时候,按钮和右边的距离很大:
方法一:如下代码所示
参考文章:http://www.jianshu.com/p/5f3eae0c0bd9
// 右侧
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//修改按钮向右移动10pt
[button setFrame:CGRectMake(10.0, 1.0, 60, 25)];
[button setTitle:@"私信HR" forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"com_sendToHr_Btn"] forState:UIControlStateNormal];
[button setTitleColor:kBlackColor forState:UIControlStateNormal];
button.titleLabel.font = KFontWithSize(12);
[button addTarget:self action:@selector(sendPrivateLetter) forControlEvents:UIControlEventTouchUpInside];
//把button添加到view中
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 60.0, 25.0)];
view.backgroundColor = [UIColor redColor];
[view addSubview:button];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
图片:
把红色去掉之后:
方法二:代码如下所示:
// 右侧
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//修改按钮向右移动10pt
[button setFrame:CGRectMake(0, 0, 60, 25)];
[button setTitle:@"私信HR" forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"com_sendToHr_Btn"] forState:UIControlStateNormal];
[button setTitleColor:kBlackColor forState:UIControlStateNormal];
button.titleLabel.font = KFontWithSize(12);
[button addTarget:self action:@selector(sendPrivateLetter) forControlEvents:UIControlEventTouchUpInside];
/******/
UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:button];
//增加一个UIBarButtonItem.
UIBarButtonItem *nagetiveSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
//这个值可以根据自己需要自己调整
nagetiveSpacer.width = -10;
self.navigationItem.rightBarButtonItems = @[nagetiveSpacer, rightItem];
/******/
效果: