2

我用下面的代码创建了一个自定义后退按钮,但是可点击区域非常大,远远超出了图标本身。有谁知道如何设置可点击区域,或使其与图像大小相同?

谢谢

UIImage *buttonImage = [UIImage imageNamed:@"prefs"];

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

[button setImage:buttonImage forState:UIControlStateNormal];

button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);

[button addTarget:self action: @selector(handleBackButton)
    forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];

self.navigationItem.leftBarButtonItem = customBarItem;

可点击区域显示为红色。

可点击区域

谢谢!

4

2 回答 2

6

如果您想阻止按钮以外的单击,则将自定义按钮添加到 UIView 然后将该视图设置为 barbuttonItem 的自定义视图

你的代码会变成这样:

UIImage *buttonImage = [UIImage imageNamed:@"prefs"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:buttonImage forState:UIControlStateNormal];
button.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
[button addTarget:self action: @selector(handleBackButton)
forControlEvents:UIControlEventTouchUpInside];

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height)];
[view addSubview:button];

UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:view];
self.navigationItem.leftBarButtonItem = customBarItem;

这应该对我有用。

于 2013-05-15T04:46:16.677 回答
0

@Prasad Devediga,快速版本非常有效:

        let btnName = UIButton()
        btnName.setImage(UIImage(named: "settings_filled_25"), forState: .Normal)
        btnName.frame = CGRectMake(0, 0, 30, 30)
        btnName.addTarget(self, action: Selector("toggleRight"), forControlEvents: .TouchUpInside)

        var rightView = UIView()
        rightView.frame = CGRectMake(0, 0, 30, 30)
        rightView.addSubview(btnName)

        let rightBarButton = UIBarButtonItem()
        rightBarButton.customView = rightView
        self.navigationItem.rightBarButtonItem = rightBarButton
于 2015-11-19T14:40:40.720 回答