UIbarButton图片没有显示?

时间:2014-03-19 13:42:52

标签: ios objective-c uibarbuttonitem

我创建了三个UIBarButton项目并将它们添加到UINavigation控制器中。

如果我使用此代码设置图像,按钮工作正常并显示:

[saveSearchButton setImage:[UIImage imageNamed:@"Save Search"]];

然后我想做到这一点,当按下按钮时 - 它的图像变为“选定的图像”

我是这样做的:

[butt setBackgroundImage:[UIImage imageNamed:@"myImage"] forState:UIControlStateSelected style:UIBarButtonItemStylePlain barMetrics:UIBarMetricsDefault];

然而,当我点击按钮时,它的图像不会改变(虽然,它的动作方法被调用)

我尝试将其图像设置为正常状态,如下所示:

[buttonOne setBackgroundImage:[UIImage imageNamed:@"myImage"] forState:UIControlStateNormal style:UIBarButtonItemStylePlain barMetrics:UIBarMetricsDefault];

当我使用上面的代码时,该按钮不再可见。如何更改按钮的所选图像?

以下是关于如何将按钮添加到UINavigationBar

的完整代码

创建它们......

UIBarButtonItem *buttonOne = [[UIBarButtonItem alloc]initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:@selector(buttonOnePressed)];
    UIBarButtonItem *buttonTwo = [[UIBarButtonItem alloc]initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:@selector(buttonTwoPressed)];
    UIBarButtonItem *buttonThree = [[UIBarButtonItem alloc]initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:@selector(buttonThreePressed)];

添加到数组

NSArray *barButtonItems = @[buttonOne,buttonTwo,buttonThree,];

添加到导航项

self.navigationItem.rightBarButtonItems = barButtonItems;

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

UIButton *button = [[UIButton alloc] init];

[button setImage:[UIImage imageNamed:@"myImage.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonOnePressed:)
    forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *barButton = [[UIBarButtonItem alloc]
                           initWithCustomView:button];

self.navigationItem.rightBarButtonItem = barButton;