【问题标题】:adding barButtonItems to a UINavigationBar without a Navigation Controller在没有导航控制器的情况下将 barButtonItems 添加到 UINavigationBar
【发布时间】:2013-01-24 17:13:51
【问题描述】:

我正在尝试向 uiNavigationBar 添加一些按钮,但它没有附加到导航控制器,我不希望这样。

我正在尝试在栏的左侧添加两个按钮,但我发现的唯一允许这样做的代码示例涉及使用该行

 self.navigationItem.leftBarButtonItems

显然,我的 UINavigationBar 不是 navigatinItem。

这是我创建导航栏的方式..

.h

@property (nonatomic, retain) UINavigationBar *navBar;

.m

_navBar = [[UINavigationBar alloc] init];
[_navBar setFrame:CGRectMake(0,0,self.view.bounds.size.width,52)];
[self.view addSubview:_navBar];

我见过两种将项目推送到导航栏的方法,但都不起作用。

首先是..

    UIBarButtonItem *barButton = [[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                  target:self
                                  action:@selector(buttonSettingClicked)];

    [[self navigationItem] setLeftBarButtonItem:barButton]

     self.navigationItem.leftBarButtonItems = _ArrayOfBarButtons;

两者都没有产生任何结果...我怀疑是因为我的 UINavigationBar 在技术上不是“导航项”。

那么如何将项目添加到我的 NavigationBar?

【问题讨论】:

  • 您可以从阅读 UINavigationBar 类参考的“向导航栏添加内容”部分开始。正如它所说,您需要将按钮添加到 UINavigationItem 的实例。在您的代码中,您引用了 self.navigationItem,但您从未创建一个。

标签: iphone ios objective-c xcode ipad


【解决方案1】:

你需要先创建UINavigationItem,给它添加按钮,然后再把navigationItem添加到导航栏。

[super viewDidLoad];
    _navBar = [[UINavigationBar alloc] init];
    [_navBar setFrame:CGRectMake(0,0,self.view.bounds.size.width,52)];
    [self.view addSubview:_navBar];
    UINavigationItem *navItem = [[UINavigationItem alloc]initWithTitle:@""];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(buttonSettingClicked)];
    [navItem setLeftBarButtonItem:barButton];

    [_navBar setItems:@[navItem]];

【讨论】:

  • 哦,好吧,就这么简单...谢谢你的帮助!
  • @JesseDurham,是的,是的。如果您想要多个按钮,只需创建更多按钮,使用 setLeftBarButtonItems:,并传递您的按钮数组。
【解决方案2】:
  m_navBar = [[UINavigationBar alloc] init];
  [m_navBar setFrame:CGRectMake(0,0,self.view.bounds.size.width,52)];
  [self.view addSubview:m_navBar];

  UIBarButtonItem *barButton = [[UIBarButtonItem alloc]
                                initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                target:self
                                action:@selector(buttonSettingClicked)];


  UINavigationItem* navItem = [[UINavigationItem alloc] initWithTitle:@"MyItem"];
  [m_navBar pushNavigationItem:navItem animated:NO];

  navItem.leftBarButtonItems = @[barButton, barButton];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多