ios UIBarButtonItem UINavigationBar 中的自定义视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16057567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UIBarButtonItem Custom view in UINavigationBar
提问by Hassy
I am making a custom bar buttons for uinavigationbar, I am using following code
我正在为 uinavigationbar 制作自定义栏按钮,我正在使用以下代码
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?
问题是它没有呼吁采取行动。我在做什么错?
回答by Alexander Merchi
From Apple documentation:
Initializes a new item using the specified custom view.
来自 Apple 文档:
使用指定的自定义视图初始化新项目。
- (id)initWithCustomView:(UIView *)customView
Parameters customView A custom view representing the item. Return Value Newly initialized item with the specified properties.
参数 customView 表示项目的自定义视图。返回值 具有指定属性的新初始化项。
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];
回答by Hassy
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;