objective-c以编程方式将图像添加到UINavigationBar

时间:2014-08-06 04:38:38

标签: objective-c uiimageview uiimage uinavigationbar

我尝试在导航栏的右侧添加一个暂停按钮,但我无法显示图标。这是我的代码:

- (void)viewDidLoad
{
  //create the navigation bar
  UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 30)];
  [self.view addSubview:navbar];

  //add the image to the navigation bar
  UIImageView *tileImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"glyphicons_174_pause.png"]];
  tileImageView.frame = CGRectMake(0, 0, 60, 25);
  self.navigationItem.titleView = tileImageView;
}

我在这里尝试了很多不同的东西,但似乎没有任何效果。为了简单起见,我的图像与我的所有类一起位于项目的根目录中,并确保它不是相对路径问题。我知道我在这里使用titleView,但我只想让它显示出来;之后我会弄清楚如何定位它(可能使用self.navigationItem.rightBarButtonItem wink wink

无论如何,非常感谢任何帮助!

由于

修改

最终,我认为如果可能的话,我宁愿这样做:

UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"glyphicons_174_pause.png"]]];
self.navigationItem.rightBarButtonItem = item;

但这也不起作用;图像根本没有显示......

3 个答案:

答案 0 :(得分:1)

如果您的View Controller位于导航控制器层次结构内,则只有

  

self.navigationItem.titleView = tileImageView;

会奏效。

否则,您必须将自定义视图作为titleview或barbutton项添加到NavigationBar

UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen]bounds].size.width, 30)];    [self.view addSubview:navbar]; 

UIImageView *tileImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"glyphicons_174_pause.png"]];
tileImageView.frame = CGRectMake(0, 0, 60, 25);    
[navbar addSubView:tileImageView];

问候。

答案 1 :(得分:0)

试试这个:

UIImage *img1 = [UIImage imageNamed:@"glyphicons_174_pause.png"];
UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithImage:img1 
                              style:UIBarButtonItemStylePlain
                                 target:self action:@selector(onBtnClicked:)];

self.navigationItem.rightBarButtonItem = btn;

答案 2 :(得分:0)

UINavigationBar而言,请尝试以下方法:

[myNavbar setBackgroundImage:[UIImage imageNamed: @"glyphicons_174_pause.png"] 
               forBarMetrics:UIBarMetricsDefault];