I am trying to customize the navigation bar by adding a custom button to the right BarButtonItem. Creating one is pretty straight forward.
UIImage *myImage = [UIImage imageNamed:@"menu-icon.png"]; UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom]; [myButton setFrame:CGRectMake(0, 0, myImage.size.width, myImage.size.height)]; [myButton setBackgroundImage:myImage forState:UIControlStateNormal]; UIBarButtonItem *myButtonItem = [[UIBarButtonItem alloc] initWithCustomView:myButton]; [navItem setLeftBarButtonItem:myButtonItem animated:YES];
It looks good, except that now I can not set the properties of the goal or action. The following code does nothing:
myButtonItem.target = myTarget; myButtonItem.action = @selector(myButtonAction);
I found that the reason it does not work is because I initialized the UIBarButtonItem with -initWithCustomView. The apple documentation says:
The panel button element created by this method does not call the action method of its target in response to user interaction. Instead, the panel button element expects the specified user view to process any user interactions and provide an appropriate response.
I'm a little confused about what exactly an apple means. Should I create a user control or something else? I haven't done it yet, and I'm not sure where to start.
Does anyone have any suggestions on how to do this or an alternative way to customize a custom navigation bar button?
ANSWERED ------------------------------------------- ------ ---------
You just need to add this method to UIButton:
[myButton addTarget:myTarget action:@selector(myButtonAction) forControlEvents:UIControlEventTouchUpInside]
source share