有时候因为懒不想自定义只想在原来的文字上进行修改 直接修改UIBarButtonItem的文字颜色:
[self.navigationItem.rightBarButtonItem setTintColor:[UIColor whiteColor]];
但如果想修改文字的尺寸 阴影等其他复杂效果是就找不到直接的修改方法了 但可以通过下面的方法做到:
[self.navigationItem.rightBarButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:14],NSFontAttributeName, nil] forState:UIControlStateNormal];
但是一般在viewdidload方法里,这样设置是无效的。查看苹果文档UIBarButtonItem的父类UIBarItem的title属性描述:
You should set this property before adding the item to a bar. The default value is nil.故无法修改其title,只能重置这个控件本身。
You should set this property before adding the item to a bar. The default value is nil.故无法修改其title,只能重置这个控件本身。
例如这样:
//设置rightItem;
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 40, 30);
btn.selected = NO;
[btn setTitle:@"管理" forState:UIControlStateNormal];
[btn setTitle:@"取消" forState:UIControlStateSelected];
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(tap:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
[self.navigationItem setRightBarButtonItem:rightItem];
但通过这个方法,我们往往是不能调整自定义出来的UIview距离屏幕边界的方法,对于一些比价坑*的产品经理来说,这远远不能达不到他们那颗装*的心,这个时候我们只能通过如下方法来调整整个个customView距离右边边界的值:
//设置rightBarBtnItem样式:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0, 0, 100, 30);
[btn setImage:[UIImage imageNamed:@"rightUp"] forState:UIControlStateNormal];
[btn setTitle:@"推荐奖励" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
btn.titleLabel.font = [UIFont systemFontOfSize: 15.0];
btn.titleLabel.textAlignment = NSTextAlignmentRight;
[btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
UIBarButtonItem *rewardItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
spaceItem.width = -15;
[btn addTarget:self action:@selector(pushToReward) forControlEvents:UIControlEventTouchUpInside];
self.navigationItem.rightBarButtonItems = @[spaceItem,rewardItem];
注意:这里着重强调的是给rightBarButtonItems弄成了一个数组,给它增加了一个spaceItem元素,用来控制customView距离右边的间距,本身rightBarButtonItem中包装的button距离它父控件,也就是rightBarButtonItem的值是5,当我们把width设置为-15后,相当于把整个rightBarButtonItem向右移动了10,对于特殊需求,可自行去调整.