Make custom back button's clickable area smaller in Navigation controller

北慕城南 提交于 2019-12-23 22:52:52

问题


I've created a custom back button with the code below, however the clickable area is very big and goes well beyond the icon itself. Does anyone know how to set the clickable area, or make it the same size as the image?

Thanks

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;

The clickable area is shown in red.

Thanks!


回答1:


If you want to prevent the click other than the button then add the custom button to UIView then set that view as custom view to the barbuttonItem

Your code will become like this :

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;

This should work as it worked for me.




回答2:


@Prasad Devediga, swift version works greatly:

        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


来源:https://stackoverflow.com/questions/16553844/make-custom-back-buttons-clickable-area-smaller-in-navigation-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!