自定义导航栏后退按钮命中区域

时间:2014-09-09 19:35:52

标签: ios user-interface uinavigationbar

  1. 我已经实现了自定义后退导航栏按钮。

  2. 代码:

    - (UIBarButtonItem *)logicToAddBackButton {

    UIImageView *imageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UiNavigationBack"]];
    
    UILabel *label=[[UILabel alloc] init];
    
    [label setTextColor:[UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0]];
    [label setText:@"Home"];
    [label sizeToFit];
    
    int space=6;
    label.frame=CGRectMake(imageView.frame.origin.x+imageView.frame.size.width+space, label.frame.origin.y, label.frame.size.width, label.frame.size.height);
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, label.frame.size.width+imageView.frame.size.width+space, imageView.frame.size.height)];
    
    view.bounds=CGRectMake(view.bounds.origin.x+8, view.bounds.origin.y-1, view.bounds.size.width, view.bounds.size.height);
    [view addSubview:imageView];
    [view addSubview:label];
    
    UIButton *button=[[UIButton alloc] initWithFrame:view.frame];
    [button addTarget:self action:@selector(eventBack) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    
    [UIView animateWithDuration:0.33 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        label.alpha = 0.0;
        CGRect orig=label.frame;
        label.frame=CGRectMake(label.frame.origin.x+25, label.frame.origin.y, label.frame.size.width, label.frame.size.height);
        label.alpha = 1.0;
        label.frame=orig;
    } completion:nil];
    
    UIBarButtonItem *backButton =[[UIBarButtonItem alloc] initWithCustomView:view];
    
    return backButton;
    

    }

    self.navigationItem.leftBarButtonItem = [self logicToAddBackButton];

  3. 根据逻辑,这是它的外观和工作方式。 enter image description here

  4. 问题:如果我们点击箭头的前半部分,后退按钮就不会响应。

  5. 请就此提出建议。

2 个答案:

答案 0 :(得分:3)

尝试设置按钮:

button.contentEdgeInsets = UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)

答案 1 :(得分:0)

我认为你错误地计算了某个地方的框架。 为什么不添加UIButton呢?它会更容易,但没有标签动画。

  UIButton *button = [[UIButton alloc] init];
    [button addTarget:self action:@selector(eventBack:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Home" forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"UiNavigationBack"] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
    [button sizeToFit];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:button];

    return backButton;