1

UIImageViewの背景として追加している があります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

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 に答える
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 に答える