Reputation: 4345
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?
Upvotes: 2
Views: 1744
Reputation: 2414
If I remember right, I had this problem with one of my past projects. I believe it is an issue with the 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;
Upvotes: 7
Reputation: 4552
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;
Upvotes: 1