将自定义图像分配给UIBarButtonItem

时间:2016-02-15 12:05:37

标签: objective-c 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处,按钮会触发操作但图像不会显示。

我如何实现这两个目标?

4 个答案:

答案 0 :(得分:1)

简单代码:

[self.sanghaNavigationButton setImage:sanghaImage];

完成这项工作。当然假设按钮已经在故事板上,并且有一个插座,就像我自己的情况一样。

答案 1 :(得分:0)

试试这个。

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];

答案 2 :(得分:0)

首先确定

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

 self.sanghaNavigationButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"myButtonImage"] style:(UIBarButtonItemStylePlain) target:self action:@selector(myAction)];   
 self.navigationItem.rightBarButtonItem = self.sanghaNavigationButton;

答案 3 :(得分:0)

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];