简体   繁体   English

iOS:自定义图像UIBarButtonItem不响应触摸

[英]iOS: Custom image UIBarButtonItem does not respond to touches

I'm attempting to use images as buttons in my nav bar. 我正在尝试将图像用作导航栏中的按钮。 The buttons display just fine, but they don't respond to touch events. 按钮显示正常,但它们不响应触摸事件。 Here's how I'm setting up the buttons: 这是我设置按钮的方式:

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);

What am I missing? 我错过了什么?

If I remember right, I had this problem with one of my past projects. 如果我没记错的话,我在过去的一个项目中遇到了这个问题。 I believe it is an issue with the UIBarButtonItem . 我相信这是UIBarButtonItem一个问题。 The workaround would be... 解决方法是......

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];

//Add it to your bar or whatever here. //将它添加到您的栏或此处的任何内容。

If you want the white glow like the regular buttons, you'll have to set 如果你想像常规按钮一样白色发光,你必须设置

imageButton.showsTouchWhenHighlighted = YES;

Try this instead, I think the issue is that you're setting the image object instead of a button object. 试试这个,我认为问题是你正在设置图像对象而不是按钮对象。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM