以编程方式将按钮添加到导航栏 [英] Add button to navigationbar programmatically

查看:79
本文介绍了以编程方式将按钮添加到导航栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式将右侧的按钮设置在导航栏中,以便如果按下按钮,我将执行一些操作.我已经通过编程方式创建了导航栏;

Hi I need to set the button on right side, in navigation bar, programatically , so that if I press the button I will perform some actions. I have created the navigation bar, programatically by;

navBar=[[UINavigationBar alloc]initWithFrame:CGRectMake(0,0,320,44) ];

类似地,我需要在此导航栏的右侧添加按钮.为此,

Similarly, I need to add the button, on the right side of this navigation bar. For that I used,

1. 

    UIView* container = [[UIView alloc] init];

    // create a button and add it to the container
    UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 130, 44.01)];
    [container addSubview:button];
    [button release];

    // add another button
    button = [[UIButton alloc] initWithFrame:CGRectMake(160, 0, 50, 44.01)];
    [container addSubview:button];
    [button release];

    // now create a Bar button item
    UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithCustomView:container];

    // set the nav bar's right button item
    self.navigationItem.rightBarButtonItem = item;
    [item release];

2. 

    UIImage *im;
    im=[UIImage imageNamed:@"back.png"];
    [button setImage:im forState:UIControlStateNormal];
    [im release];
    backButton = [[UIBarButtonItem alloc] initWithCustomView:button];       
    [backButton setImageInsets:UIEdgeInsetsMake(0, -10,5, 5)];
    [self.navigationItem setRightBarButtonItem:backButton];

3. 

    UIBarButtonItem *refreshItem = [[UIBarButtonItem alloc] initWithTitle:@"button"               style:UIBarButtonItemStylePlain target:self action:@selector(refreshLogsAction:)];
    self.navigationItem.rightBarButtonItem = refreshItem;

    [refreshItem release];

我尝试了所有这些方法,但是没有一个在右侧显示按钮.

I tried all these ways, but none is displaying the button on the right hand side.

推荐答案

在我的UIViewController派生类中,我在viewDidLoad中使用以下内容:

Inside my UIViewController derived class, I am using the following inside viewDidLoad:

UIBarButtonItem *flipButton = [[UIBarButtonItem alloc] 
                               initWithTitle:@"Flip"                                            
                               style:UIBarButtonItemStyleBordered 
                               target:self 
                               action:@selector(flipView:)];
self.navigationItem.rightBarButtonItem = flipButton;
[flipButton release];

这会在右侧添加一个名为Flip的按钮,该按钮将调用方法:

This adds a button to the right hand side with the title Flip, which calls the method:

-(IBAction)flipView

这看起来非常像您#3,但它在我的代码中有效.

This looks very much like you #3, but it is working within my code.

这篇关于以编程方式将按钮添加到导航栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆