如何更改UIBarButtonItem的选择区域?

时间:2016-05-06 17:40:55

标签: ios swift uinavigationcontroller uibarbuttonitem

我正在尝试更改导航控制器中UIBarButtonItem的选择区域。基本上我正在尝试更改允许UIBarButtonItem可选的允许区域。现在,UIBarButtonItem的大小是40x40,但即使我的手指根本没有碰到按钮,我也可以轻松选择它。

这是为了说明我的意思:

enter image description here

绿色代表UIBarButtonItem的大小。红色表示允许UIBarButtonItem可选的允许区域。

如何更改红色区域的宽度?

如果有帮助的话,这里有一段代码:

changeMuscleMap = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40) )
changeMuscleMap.setImage(UIImage(named: "change"), forState: .Normal)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: changeMuscleMap)

谢谢!

4 个答案:

答案 0 :(得分:0)

您可以使用以下代码增加或减少UIBarButtonItem按钮宽度。

changeMuscleMap = UIButton(frame: CGRect(x: 0, y: 0, width: 120, height: 40) )
changeMuscleMap.setImage(UIImage(named: "change"), forState: .Normal)
changeMuscleMap.contentHorizontalAlignment = .left
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: changeMuscleMap)

答案 1 :(得分:0)

如果您想要比所需更大的点击区域,请尝试以下代码,然后使用自定义按钮制作UIBarButtonItem:

@implementation CustomButton

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
    UIEdgeInsets extendTouchInsets = UIEdgeInsetsMake(20, 0, 20, 0);
    CGRect bounds = self.bounds;
    bounds.origin.x -= extendTouchInsets.left;
    bounds.origin.y -= extendTouchInsets.top;
    bounds.size.width += extendTouchInsets.left + extendTouchInsets.right;
    bounds.size.height += extendTouchInsets.top + extendTouchInsets.bottom;
    return CGRectContainsPoint(bounds, point);
}

@end

答案 2 :(得分:-1)

可以通过将自定义项UIBarButtonItem设为UIImageView而不是UIButton来实现。请尝试以下代码。我希望现在能解决这个问题。

changeMuscleMap = UIImageView(image:UIImage(named: "change"))
imageView.frame = CGRectMake(0, 0, 40, 40)
let leftBarBtn = UIBarButtonItem(customView: imageView)
self.navigationItem.leftBarButtonItem = leftBarBtn

答案 3 :(得分:-3)

通过使用@Damien Romito提供的答案,我能够实现我想要的目标:

UINavigationBar UIBarButtonItems much larger click area than required

针对Swift 3.0进行了更新:

let buttonContainer: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 27, height: 30) )

let barButton: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30) )

buttonContainer.addSubview(barButton)

barButton = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

barButton(#imageLiteral(resourceName: "image"), for: UIControlState.normal)

self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: buttonContainer)

barButton(self, action: #selector(ViewController.doSomething), for: UIControlEvents.touchUpInside)