设置导航条左右按钮

今天在做项目的时候发现一个问题,在设置导航栏左边按钮(导航栏上面的东西由栈顶控制器决定)的时候,如果是用UIButton包装成UIBarButtonItem设置为导航条左边的按钮,那么会导致按钮可点击范围增大,这样的用户体验是非常不好的,下面是出问题的源码:
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    // 设置导航条按钮
    [self setUpNavBar];

}

- (void)setUpNavBar
    {
        UIButton *btn = [[UIButton alloc] init];
        [btn setImage:[UIImage imageNamed:@"nav_item_game_icon"] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"nav_item_game_click_icon"] forState:UIControlStateHighlighted];
        [btn sizeToFit];
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
        self.navigationItem.leftBarButtonItem = item;
}  
  • 之后我采用UIView包装UIButton在把UIView包装成UIBarButtonItem设置为导航条左边的按钮,点击范围就正常了
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 设置导航条按钮
    [self setUpNavBar];

}

- (void)setUpNavBar
{
    UIButton *btn = [[UIButton alloc] init];
    [btn setImage:[UIImage imageNamed:@"nav_item_game_icon"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"nav_item_game_click_icon"] forState:UIControlStateHighlighted];
    [btn sizeToFit];
    // 添加的代码
    UIView *itemView = [[UIView alloc] initWithFrame:btn.bounds];
    [itemView addSubview:btn];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:itemView];
    self.navigationItem.leftBarButtonItem = item;
}

你可能感兴趣的:(设置导航条左右按钮)