将自定义图像分配给 UIBarButtonItem

Assigning custom image to UIBarButtonItem

我正在尝试将自定义动态图像分配给导航项;通过执行以下操作,图像显示但按钮不会触发其操作 - 它甚至不会注册点击,因为它已被禁用:

-(void) updateSanghaButton{
    UIImage* sanghaImage=[[SanghaModelProvider sharedProvider] burnedImageForMeditators];
    UIImageView* sanghaView=[[UIImageView alloc] initWithImage:sanghaImage];
    self.sanghaNavigationButton.customView=sanghaView;
    self.sanghaNavigationButton.target=self;
    self.sanghaNavigationButton.action=@selector(showSangha:);
    self.sanghaNavigationButton.enabled=YES;
}

相反,如果我使用代码:

UIBarButtonItem *graphButton = [[UIBarButtonItem alloc] initWithImage:   [UIImage imageNamed:@"GraphButton.png"]
                                                             style:UIBarButtonItemStyleBordered
                                                               target:self
                                                               action:@selector(graphButton)];
self.navigationItem.rightBarButtonItem = graphButton;

UIBarButtonItem Custom view in UINavigationBar 相同,按钮触发了操作但未显示图像。

如何实现这两个目标?

简单代码:

[self.sanghaNavigationButton setImage:sanghaImage];

刚刚好。当然假设按钮已经在情节提要板上并且有一个出口,就像我自己的情况一样。

试试这个。

UIButton *btnSetting = [UIButton buttonWithType:UIButtonTypeCustom];
        [btnSetting setBackgroundImage:imgSetting forState:UIControlStateNormal];
        btnSetting.frame = CGRectMake(0, 7, imgSetting.size.width, imgSetting.size.height);
        [btnSetting addTarget:self action:@selector(showSangha:) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *rightbaritem=[[UIBarButtonItem alloc]initWithCustomView:btnSetting];

 self.navigationItem.rightBarButtonItems=@[rightbaritem];

首先确定

关于你的 UIImage 不是 nil 。 之后你可以通过这种方式设置带有自定义图像的导航栏:

 self.sanghaNavigationButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"myButtonImage"] style:(UIBarButtonItemStylePlain) target:self action:@selector(myAction)];   
 self.navigationItem.rightBarButtonItem = self.sanghaNavigationButton;
UIImage* imagebackbutton = [UIImage imageNamed:@"splace_logo"];
    UIButton *btnback = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [btnback setBackgroundImage:imagebackbutton forState:UIControlStateNormal];
    [btnback addTarget:self action:@selector(goBack:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *mailbutton =[[UIBarButtonItem alloc] initWithCustomView:btnback];