Smaller active area for custom UIBarButtonItem

后端 未结 3 1887
面向向阳花
面向向阳花 2021-02-10 01:17

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 t

3条回答
  •  感动是毒
    2021-02-10 01:44

    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];
    

提交回复
热议问题