我正在尝试将图像用作导航栏中的按钮。按钮显示正常,但它们不响应触摸事件。以下是我设置按钮的方法:
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);
我错过了什么?
答案 0 :(得分: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;
答案 1 :(得分: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;