objective-c - 以编程方式将按钮添加到导航栏

标签 objective-c iphone uinavigationbar uibarbuttonitem

您好,我需要在右侧的导航栏中以编程方式设置按钮,这样如果我按下按钮,我将执行一些操作。我以编程方式创建了导航栏;

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

同样,我需要在此导航栏的右侧添加按钮。对于我使用的,

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

我尝试了所有这些方法,但都没有显示右侧的按钮。

最佳答案

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

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

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

-(IBAction)flipView

这看起来很像你#3,但它在我的代码中工作。

关于objective-c - 以编程方式将按钮添加到导航栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2848055/

相关文章:

iphone - UICollectionViewContoller单元格格式和安排

ios - 无法更改状态栏样式

ios - 如何在 iOS 7 的导航栏上获得模糊和半透明的效果?

ios - 在 Objective-C 中将两个 uint8_t 转换/组合为 int16_t

objective-c - 如何实现一个 iOS 表格 View ,旁边带有字母以供导航?

ios - 如何让对象对 Cocos2D 中的触摸使用react?

iphone - UITextView 文本不是从顶部开始

iphone - 使用加速计退出 View 时崩溃

iphone - iOS SDK 彩信视频流

ios - 如何在 Swift 中仅删除 NavigationBar 的边框颜色?