20

我正在为 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;

问题是它没有采取行动。我做错了什么?

4

2 回答 2

51

来自 Apple 文档:
使用指定的自定义视图初始化新项目。

- (id)initWithCustomView:(UIView *)customView

参数 customView 表示项目的自定义视图。返回值 具有指定属性的新初始化项。

讨论: 此方法创建的条形按钮项不会调用其目标的操作方法来响应用户交互。相反,条形按钮项期望指定的自定义视图来处理任何用户交互并提供适当的响应。

解决方案:“使用您的背景图像创建按钮(为此按钮设置操作)并使用此按钮初始化栏按钮”。例如:

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];
于 2013-04-17T12:20:27.203 回答
1

我使用以下代码完成了此操作:

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;
于 2013-04-17T11:04:44.773 回答