UIBarButtonItem点击范围过大

解决NavgationBar里面UIBarButtonItem点击范围过大的问题

问题

大家肯定都自定义过NavgationBar的返回按钮吧,按照下面方法设置的时候,会有点击范围过大的问题

    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 30, 30);
    leftButton.backgroundColor = [UIColor redColor];
    [leftButton addTarget:self action:@selector(leftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftItem;
UIBarButtonItem点击范围过大_第1张图片
Paste_Image.png

解决

在Button外面包一层View就可以了,就会是正常的Button的点击范围了

    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 30, 30);
    leftButton.backgroundColor = [UIColor redColor];
    [leftButton addTarget:self action:@selector(leftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *menuButtonContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [menuButtonContainer addSubview:leftButton];
    
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:menuButtonContainer];
    self.navigationItem.leftBarButtonItem = leftItem;

观察

尝试了好多应用,基本上都有这个现象,不是很细心的人根本发现不了,但是我开发的APP返回按钮给的图片太小了 效果十分明显的,找到解决方法以后,发现按钮太小了,button的frame是根据图片大小来的,不打算改成正常的了 (;¬_¬)

你可能感兴趣的:(UIBarButtonItem点击范围过大)