如何以编程设置画面中的NavBar?(How to set a picture programmat

2019-06-21 06:18发布

我有一种观点与后退按钮导航栏和名称的DetailView。 导航栏编程设置。 提出的名称设置是这样的。

self.title = NSLocalizedString(name, @"");

名称取决于所提出的观点。

现在,我想也呈现导航栏这也是依赖于视图上的一个小图标。

我怎么做?

Answer 1:

您可以设置背景图片的导航栏使用此

放入didFinishLaunchingWithOptions

[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"title_bar.png"] forBarMetrics:UIBarMetricsDefault];  

或者你可以在任何视图中使用设置导航栏图像

UINavigationBar *navBar = [[self navigationController] navigationBar];
    UIImage *image = [UIImage imageNamed:@"TopBar.png"];
    [navBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];

或者可以在导航栏设置视图 链接

[[UINavigationBar appearance] addSubview:yourView]; 

要么

self.navigationItem.titleView = YourView;  

并采用H 设置标题

self.navigationItem.title = @"Your Title"; 

你可以得到使用此navigationBarButton

-(void)getRightBarBtn
{
    UIButton *Btn =[UIButton buttonWithType:UIButtonTypeCustom];

    [Btn setFrame:CGRectMake(0.0f,0.0f,68.0f,30.0f)];
    [Btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"yourImage.png"]]  forState:UIControlStateNormal];
    //[Btn setTitle:@"OK" forState:UIControlStateNormal];
    //Btn.titleLabel.font = [UIFont fontWithName:@"Georgia" size:14];
    [Btn addTarget:self action:@selector(yourBtnPress:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithCustomView:Btn];
    [self.navigationItem setRightBarButtonItem:addButton];
}

并设置导航栏简单的ImageView

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


Answer 2:

你需要继承UINavigationBar的。 然后,在drawRect中做这样的事情:

[[UIImage imageNamed...] drawInRect:...]

并调用超级方法ofcourse



Answer 3:

这段代码添加到viewDidLoad在你的ViewController:

UIImage *image = [UIImage imageNamed: @"myIcon.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(5, 2, 100, 39);
[self.navigationController.navigationBar addSubview:imageView];

ImageView的也可以声明为一个实例变量,所以(如果你想在某个时候从您的导航栏删除您的图标如),您可以访问您已加入后。



Answer 4:

UIButton *homeBtn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 46, 28)];
[homeBtn setBackgroundImage:[UIImage imageNamed:@"homeBtn.png"] forState:UIControlStateNormal];    
[homeBtn addTarget:self action:@selector(homeBtnPressed) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *navHomeBtn=[[[UIBarButtonItem alloc] initWithCustomView:homeBtn] autorelease];    
self.navigationItem.rightBarButtonItem=navHomeBtn;   
[homeBtn release];


文章来源: How to set a picture programmatically in a NavBar?