iOS OC 导航栏自定义rightBarButtonItem
UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)]; customView.backgroundColor = [UIColor lightGrayColor]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 34, 80, 10)]; label.text = @"Custom"; label.textAlignment = NSTextAlignmentCenter; [customView addSubview:label]; UIImage *image = [UIImage imageNamed:@"collect"]; UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setFrame:CGRectMake(33, 0, 34, 34)]; [button setImage:image forState:UIControlStateNormal]; [button addTarget:self action:@selector(collectBtnClicked) forControlEvents:UIControlEventTouchUpInside]; [customView addSubview:button]; UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:customView]; self.navigationItem.rightBarButtonItem = barButtonItem;//rightBarButtonItems是一样的(多个的时候用s)
下面我自己用的
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)]; containerView.backgroundColor = [UIColor clearColor]; [containerView addSubview:self.customerServiceButton]; // 将自定义按钮添加到UIBarButtonItem中 UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:containerView]; // 将按钮添加到导航项的右侧 self.navigationItem.rightBarButtonItems = @[rightBarButton];
@property (nonatomic, strong) QMUIButton *customerServiceButton;//客服按钮
#pragma mark - Setter && Getter 懒加载 //客服按钮 -(QMUIButton *)customerServiceButton{ if (!_customerServiceButton) { _customerServiceButton = [QMUIButton buttonWithType:UIButtonTypeCustom]; [_customerServiceButton setFrame:CGRectMake(76, 10, 24, 24)]; [_customerServiceButton setImage:UIImageMake(@"下载 2") forState:UIControlStateNormal]; [_customerServiceButton addTarget:self action:@selector(customerServiceButtonEvent) forControlEvents:UIControlEventTouchUpInside]; } return _customerServiceButton; } - (void)customerServiceButtonEvent{ NSLog(@"用户点击了客服按钮888"); ZXJKeFuViewController *vc= [[ZXJKeFuViewController alloc] init]; [self.navigationController pushViewController:vc animated:YES]; }
有人这样写
- (void)createRightItem{ self.navigationItem.rightBarButtonItem = [UIBarButtonItem qmui_itemWithImage:UIImageMake(@"下载 2") target:self action:@selector(rightClick)]; self.navigationItem.rightBarButtonItem.tintColor = UIColorMakeWithHex(@"#292929"); } - (void)rightClick{ [self addNewAdsClick]; } - (void)addNewAdsClick { ZXJKeFuViewController* vc= [[ZXJKeFuViewController alloc] init]; [self.navigationController pushViewController:vc animated:YES]; }
也是可以的