1

我有一个UIImageView,我将其添加为 a 的背景UIBarButtonItem。我将 UIBarButtonItem 作为导航控制器的右侧 barbuttonitem。我在调试时无法处理UIBarButtonItem单击事件,因为控件没有进入方法。这可能是什么原因?

UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,32,32)];
    [myImage setImage:[UIImage imageNamed:@"logo.png"]];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:myImage];
    //rightBarButton.target = self;
    //rightBarButton.action = @selector(onMyMethod);
    if(isRight){
        self.navigationItem.rightBarButtonItem = rightBarButton;
        self.navigationItem.rightBarButtonItem.target = self;
        self.navigationItem.rightBarButtonItem.action = @selector(onMyMethod);
    }
4

3 回答 3

2

我认为使用 UIBarButton 的 initWithCustomView 时目标和操作不起作用,因此您可以使用类似的东西-

UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,32,32)];
[myImage setImage:[UIImage imageNamed:@"logo.png"]];

UIButton* rightButton = [UIButton buttonWithType: UIButtonTypeInfoLight];
[rightButton addTarget:self 
                action:@selector(onMyMethod:) 
      forControlEvents:UIControlEventTouchDown];


UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
于 2012-04-13T10:39:09.200 回答
1

编辑您的代码:

UIImageView *myImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,32,32)];
myImage. userInteractionEnabled = Yes;
[myImage setImage:[UIImage imageNamed:@"logo.png"]];
UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:myImage];

if(isRight)
{
    self.navigationItem.rightBarButtonItem = rightBarButton;
    self.navigationItem.rightBarButtonItem.target = self;
    self.navigationItem.rightBarButtonItem.action = @selector(onMyMethod:);
}

试试这个谢谢:)

于 2012-04-13T10:06:06.513 回答
1

按照 RIP 的回答,我更改了UIBarButtonItem并创建了一个UIButton并将其添加为导航控制器的子视图

        UIImage *image = [UIImage imageNamed:@"logo.png"];

        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setBackgroundImage:image forState:UIControlStateNormal];

        [button addTarget:self action:@selector(onMyMethod:)  forControlEvents:UIControlEventTouchUpInside];
        CGRect frame = CGRectMake(260.0, 7.0, 32.0, 32.0);
        button.frame = frame;
        [button setBackgroundImage:image forState:UIControlStateNormal];
        [self.navigationController.navigationBar addSubview:button];
于 2012-04-14T04:18:24.080 回答