2

我正在尝试将图像用作导航栏中的按钮。按钮显示得很好,但它们不响应触摸事件。这是我设置按钮的方式:

UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow_up_24.png"]];

iv.userInteractionEnabled=YES;
UIBarButtonItem * logoutButton = [[UIBarButtonItem alloc] initWithCustomView:iv ];

logoutButton.target=self;
logoutButton.action=@selector(logoutButtonPressed);

我错过了什么?

4

2 回答 2

7

如果我没记错的话,我在过去的一个项目中遇到了这个问题。我相信这是一个问题UIBarButtonItem。解决方法是...

UIButton *imageButton = [UIButton buttonWithStyle:UIButtonStyleCustom];
imageButton.frame = CGRectMake(0,0,24,24);//Standard size of a UIBarButtonItem i think.
[imageButton setImage:[UIImage imageNamed:@"arrow_up_24.png"] forState:UIControlStateNormal];
[imageButton addTarget:self action:@selector(logoutButtonPressed) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:imageButton];

//将其添加到您的酒吧或此处的任何内容。

如果你想要像普通按钮一样的白光,你必须设置

imageButton.showsTouchWhenHighlighted = YES;
于 2012-11-15T15:13:52.630 回答
1

试试这个,我认为问题在于你设置的是图像对象而不是按钮对象。

UIButton *navBarButton = [[UIButton alloc] init];
[navBarButton setImage:[UIImage imageNamed:@"arrow_up_24.png"] forState:UIControlStateNormal];
[navBarButton addTarget:self action:@selector(logoutButtonPressed) forControlEvents:UIControlEventTouchUpInside];

// Use self.navigationItem.leftBarButtonItem if that's your preference
UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightItemImage];
self.navigationItem.rightBarButtonItem = rightItem;
于 2012-11-15T15:09:05.160 回答