开发者

Smaller active area for custom UIBarButtonItem

开发者 https://www.devze.com 2022-12-21 14:57 出处:网络
I have a UINavigationBar with a custom UIBarButtonItem (which uses a UIButton as its custom view). The problem is: the active area of the custom button is much too large, if I tap at least 40 pixels o

I have a UINavigationBar with a custom UIBarButtonItem (which uses a UIButton as its custom view). The problem is: the active area of the custom button is much too large, if I tap at least 40 pixels outside the button, it still gets registered as a tap on the button. This results in accidental t开发者_StackOverflowaps. How can I reduce the active area on these buttons?


I noticed this weirdness too. I found that using a container UIView fixes this. For example:

UIButton *menuButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
[menuButton addTarget:self action:@selector(revealMenu:) forControlEvents:UIControlEventTouchUpInside];
[menuButton setImage:[UIImage imageNamed:@"menuIcon"] forState:UIControlStateNormal];
UIView *menuButtonContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
[menuButtonContainer addSubview:menuButton];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:menuButtonContainer];


I think u haven't changed the size of the custom button... Try doing this... In Interface builder select the button which u want to reduce the active area and then press "Command+3" or "tools --> Size inspector" in that reduce 'W' and 'H' values... this will make the custom button smaller and so the active area also get reduced...

~Raviraja


Are you adding the button through Interface Builder or are you doing it programmatically? Either way, you can use this line of code to set the bounds of the image:

yourButton.bounds = CGRectMake( 0, 0, yourImage.size.width, yourImage.size.height );  

If you want a full example, here's one I used in one of my apps:

    UIImage *image = [UIImage imageNamed:@"audio-off.png"];
    UIButton *myMuteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    myMuteButton.bounds = CGRectMake( 0, 0, image.size.width, image.size.height );    
    [myMuteButton setImage:image forState:UIControlStateNormal];
    [myMuteButton addTarget:self action:@selector(mute) forControlEvents:UIControlEventTouchUpInside];    
    UIBarButtonItem *myMuteBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myMuteButton];   
    navBar.leftBarButtonItem = myMuteBarButtonItem;
    [myMuteBarButtonItem release];
0

精彩评论

暂无评论...
验证码 换一张
取 消