UIBarButtonItem Custom view in UINavigationBar

戏子无情 提交于 2019-11-26 20:54:02

问题


I am making a custom bar buttons for uinavigationbar, I am using following code

 UIImageView *backImgView= [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chk_back.png"]]; [backImgView setUserInteractionEnabled:YES];
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:backImgView];
[backButton setTarget:self];
[backButton setAction:@selector(BackBtn)];
checkIn_NavBar.topItem.leftBarButtonItem = backButton;

The problem is it is not calling its action. What i am doing wrong?


回答1:


From Apple documentation:
Initializes a new item using the specified custom view.

- (id)initWithCustomView:(UIView *)customView

Parameters customView A custom view representing the item. Return Value Newly initialized item with the specified properties.

Discussion: The bar button item created by this method does not call the action method of its target in response to user interactions. Instead, the bar button item expects the specified custom view to handle any user interactions and provide an appropriate response.

Solution: "Create button with your background image (set action to this button) and init bar button with this button". For example:

UIButton *btn =  [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0,0,25,25)
[btn setBackgroundImage:[UIImage imageNamed:@"chk_back.png"] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(BackBtn) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];



回答2:


UIBarButtonItem *graphButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"GraphButton.png"]
                                                                    style:UIBarButtonItemStyleBordered
                                                                   target:self
                                                                   action:@selector(graphButton)];
self.navigationItem.rightBarButtonItem = graphButton;

- (void)graphButton{
}



回答3:


I accomplished this using following code:

UIButton *nxtBtn =  [UIButton buttonWithType:UIButtonTypeCustom];
[nxtBtn setImage:[UIImage imageNamed:@"chk_next.png"] forState:UIControlStateNormal];
[nxtBtn addTarget:self action:@selector(NextBtn) forControlEvents:UIControlEventTouchUpInside];
[nxtBtn setFrame:CGRectMake(0, 0, 64, 31)];
UIBarButtonItem *nextButton = [[UIBarButtonItem alloc] initWithCustomView:nxtBtn];

checkIn_NavBar.topItem.rightBarButtonItem=nextButton;


来源:https://stackoverflow.com/questions/16057567/uibarbuttonitem-custom-view-in-uinavigationbar

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