如何向UINavigationController添加右键?


191

我试图将刷新按钮添加到导航控制器的顶部栏中,但没有成功。

这是标题:

@interface PropertyViewController : UINavigationController {

}

这是我尝试添加的方式:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain
                                          target:self action:@selector(refreshPropertyList:)];      
        self.navigationItem.rightBarButtonItem = anotherButton;
    }
    return self;
}

Answers:


362

尝试在viewDidLoad中进行操作。通常,无论如何,您应该将任何事情都推迟到那一点为止,当UIViewController初始化时,它可能还需要相当长的时间才能显示出来,没有必要尽早进行工作并占用内存。

- (void)viewDidLoad {
  [super viewDidLoad];

  UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain target:self action:@selector(refreshPropertyList:)];          
  self.navigationItem.rightBarButtonItem = anotherButton;
  // exclude the following in ARC projects...
  [anotherButton release];
}

至于为什么它目前无法正常工作,我不能在没有看到更多代码的情况下100%地确定,但是在初始化和加载视图之间会发生很多事情,您可能正在做一些事情导致NavigationItem重置为之间。


45
我在UINavigationController子类外部进行此操作,您将像这样引用它:someNavController.topLevelController.navigationItem.rightBarButtonItem = anotherButton
ransomweaver 2010年

2
我正在实施建议的解决方案,但我的应用程序一直崩溃,直到意识到@selector方法名称必须以冒号(:)结尾。
2012年

10
即使在UINavigationContoller的viewDidLoad方法内部,我也必须这样称呼它self.topViewController.navigationItem.leftBarButtonItem = nextButton;
Joseph

谢谢!@约瑟夫,您的澄清救了我。(y):)
Prasanna

38

尝试将按钮添加到将要推到该按钮的视图控制器的navigationItem中 PropertyViewController您创建的。

那是:

MainViewController *vc = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
[infoButton addTarget:self action:@selector(showInfo) forControlEvents:UIControlEventTouchUpInside];
vc.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:infoButton] autorelease];

PropertyViewController *navController = [[PropertyViewController alloc] initWithRootViewController:vc];

现在,以编程方式创建的此infoButton将显示在导航栏中。这个想法是导航控制器从将UIViewController要显示的内容中获取其显示信息(标题,按钮等)。您实际上并没有直接在中添加按钮等UINavigationController


2
直接在UINavigationController上设置rightBarButtonItem对我不起作用(如上面的Louis Gerbarg所建议的)。而是像Adem建议的那样直接在UIViewController上直接设置项目!
leviathan

4
“尝试将按钮添加到要按下的视图控制器的navigationItem中” +1 !
2013年

25

似乎有些人(例如我)可能会来这里寻找如何在Interface Builder中添加导航栏按钮。下面的答案显示了如何执行此操作。

将导航控制器添加到情节提要

选择您的View Controller,然后在Xcode菜单中选择Editor> Embed In> Navigation Controller

在此处输入图片说明

或者,您可以UINavigationBar从对象库中添加一个。

添加条形按钮项

将a UIBarButtonItem从“对象库”拖到顶部导航栏。

在此处输入图片说明

它看起来应该像这样:

在此处输入图片说明

设置属性

你可以双击“项目”来改变文字的东西,如“刷新”,但对于实际的图标刷新,您可以使用。只需为选择Attributes Inspector,UIBarButtonItem然后为System Item选择Refresh

在此处输入图片说明

这将为您提供默认的刷新图标。

在此处输入图片说明

添加IB动作

将控件从拖动UIBarButtonItem到视图控制器以添加一个@IBAction

class ViewController: UIViewController {

    @IBAction func refreshBarButtonItemTap(sender: UIBarButtonItem) {
        
        print("How refreshing!")
    }
    
}

而已。


抱歉,我不太明白您的意思。尝试用说明您正在谈论的图像的新问题。然后在此处添加链接。
Suragch '16

@Suragch,我如何用xib文件而不是情节提要板做同样的事情?,谢谢
Cristian Chaparro A.

@CristianChaparroA。通常,xib文件用于单个视图,而导航栏(包含栏按钮项)用于多个视图。我从未使用带有条形按钮项目的xib。您可以尝试问一个新问题,然后在此处链接到它。
Suragch '16

14

没有用于“刷新”的默认系统按钮:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIBarButtonItem *refreshButton = [[[UIBarButtonItem alloc] 
                            initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
                            target:self action:@selector(refreshClicked:)] autorelease];
    self.navigationItem.rightBarButtonItem = refreshButton;

}

- (IBAction)refreshClicked:(id)sender {

}

11

您可以使用此:

物镜

UIBarButtonItem *rightSideOptionButton = [[UIBarButtonItem alloc] initWithTitle:@"Right" style:UIBarButtonItemStylePlain target:self action:@selector(rightSideOptionButtonClicked:)];          
self.navigationItem.rightBarButtonItem = rightSideOptionButton;

迅速

let rightSideOptionButton = UIBarButtonItem()
rightSideOptionButton.title = "Right"
self.navigationItem.rightBarButtonItem = rightSideOptionButton

6
-(void) viewWillAppear:(BOOL)animated
{

    UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnRight setFrame:CGRectMake(0, 0, 30, 44)];
    [btnRight setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
    [btnRight addTarget:self action:@selector(saveData) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBtnRight = [[UIBarButtonItem alloc] initWithCustomView:btnRight];
    [barBtnRight setTintColor:[UIColor whiteColor]];
    [[[self tabBarController] navigationItem] setRightBarButtonItem:barBtnRight];

}

谁能告诉我有什么坏处做在viewWillAppear中,而不是viewDidLoad中
NIRANJAN Molkeri

6

快速2:

self.title = "Your Title"

var homeButton : UIBarButtonItem = UIBarButtonItem(title: "LeftButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("yourMethod"))

var logButton : UIBarButtonItem = UIBarButtonItem(title: "RigthButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("yourMethod"))

self.navigationItem.leftBarButtonItem = homeButton
self.navigationItem.rightBarButtonItem = logButton

我建议使用新的swift2选择器:#selector(classname.functionname)
空无一人

5

这是Swift中的解决方案(根据需要设置选项):

var optionButton = UIBarButtonItem()
optionButton.title = "Settings"
//optionButton.action = something (put your action here)
self.navigationItem.rightBarButtonItem = optionButton

4

为什么是子类UINavigationController?如果您需要做的就是添加一个按钮,则无需对其进行子类化。

设置一个层次结构UINavigationController,其顶部为a ,然后在您的根视图控制器的viewDidLoad:方法中:设置该按钮,然后通过调用将其附加到导航项

[[self navigationItem] setRightBarButtonItem:myBarButtonItem];

1
这是一个好问题。我要尝试做的实际上是一个非常常见的设计模式,它是一个基本的标签控制器,每个标签都有一个导航控制器。如果有更好的方法,我欢迎您提出建议。也许我也应该问这个问题。
Artilheiro


3

斯威夫特4:

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "tap me", style: .plain, target: self, action: #selector(onButtonTap))
}

@objc func onButtonTap() {
    print("you tapped me !?")
}

如果您想要右侧按钮,则只需使用navigationItem.rightBarButtonItem
Ghanshyam Bagul,

2
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 110, 50)];
view.backgroundColor = [UIColor clearColor];

UIButton *settingsButton =  [UIButton buttonWithType:UIButtonTypeCustom];
[settingsButton setImage:[UIImage imageNamed:@"settings_icon_png.png"] forState:UIControlStateNormal];
[settingsButton addTarget:self action:@selector(logOutClicked) forControlEvents:UIControlEventTouchUpInside];
[settingsButton setFrame:CGRectMake(40,5,32,32)];
[view addSubview:settingsButton];

UIButton *filterButton =  [UIButton buttonWithType:UIButtonTypeCustom];
[filterButton setImage:[UIImage imageNamed:@"filter.png"] forState:UIControlStateNormal];
[filterButton addTarget:self action:@selector(openActionSheet) forControlEvents:UIControlEventTouchUpInside];
[filterButton setFrame:CGRectMake(80,5,32,32)];
[view addSubview:filterButton];



self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];

2

试试这个对我有用。

导航栏,还向右键添加了背景图片。

 UIBarButtonItem *Savebtn=[[UIBarButtonItem alloc]initWithImage:[[UIImage    
 imageNamed:@"bt_save.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] 
 style:UIBarButtonItemStylePlain target:self action:@selector(SaveButtonClicked)];
 self.navigationItem.rightBarButtonItem=Savebtn;

0
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add:)];
self.navigationItem.rightBarButtonItem = rightBarButtonItem;

0
- (void)viewWillAppear:(BOOL)animated
{    
    [self setDetailViewNavigationBar];    
}
-(void)setDetailViewNavigationBar
{
    self.navigationController.navigationBar.tintColor = [UIColor purpleColor];
    [self setNavigationBarRightButton];
    [self setNavigationBarBackButton];    
}
-(void)setNavigationBarBackButton// using custom button 
{
   UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"  Back " style:UIBarButtonItemStylePlain target:self action:@selector(onClickLeftButton:)];          
   self.navigationItem.leftBarButtonItem = leftButton;    
}
- (void)onClickLeftButton:(id)sender 
{
   NSLog(@"onClickLeftButton");        
}
-(void)setNavigationBarRightButton
{

  UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain target:self action:@selector(onClickrighttButton:)];          
self.navigationItem.rightBarButtonItem = anotherButton;   

}
- (void)onClickrighttButton:(id)sender 
{
   NSLog(@"onClickrighttButton");  
}

0
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshData)];



}

-(void)refreshData{
    progressHud= [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    [progressHud setLabelText:@"拼命加载中..."];
    [self loadNetwork];
}

0

您应该在- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated方法中添加barButtonItem 。


0

只需复制并粘贴此Objective-C代码即可。

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addRightBarButtonItem];
}
- (void) addRightBarButtonItem {
    UIButton *btnAddContact = [UIButton buttonWithType:UIButtonTypeContactAdd];
    [btnAddContact addTarget:self action:@selector(addCustomerPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btnAddContact];
    self.navigationItem.rightBarButtonItem = barButton;
}

#pragma mark - UIButton
- (IBAction)addCustomerPressed:(id)sender {
// Your right button pressed event
}

我正在帮助您
Vivek

0

如果我们删除视图控制器或尝试在界面生成器(main.storyboard)内添加新的视图控制器,则会发生此问题。若要解决此问题,它需要在新的视图控制器内添加“导航项”。有时,我们创建了新的视图控制器屏幕,但它没有自动连接到“导航项”。

  1. 转到main.storyboard。
  2. 选择该新视图控制器。
  3. 转到文档大纲。
  4. 检查视图控制器的内容。
  5. 如果新视图控制器没有导航项,则从以前的视图控制器复制导航项,然后将其粘贴到新视图控制器中。
  6. 保存并清理项目。

0

您也可以使用添加多个按钮 rightBarButtonItems

-(void)viewDidLoad{

    UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithTitle:@"button 1" style:UIBarButtonItemStylePlain target:self action:@selector(YOUR_METHOD1:)];
    UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithTitle:@"button 2" style:UIBarButtonItemStylePlain target:self action:@selector(YOUR_METHOD2:)];

    self.navigationItem.rightBarButtonItems = @[button1, button2];
}

-1

@Artilheiro:如果它是基于导航的项目,则可以创建BaseViewController。所有其他视图将继承此BaseView。在BaseView中,您可以定义通用方法来添加右按钮或更改左按钮文本。

例如:

@interface BaseController:UIViewController {

}-(void)setBackButtonCaption:(NSString *)caption;

(void)setRightButtonCaption:(NSString *)字幕选择器:(SEL)选择器;

@end //在BaseView.M中

(void)setBackButtonCaption:(NSString *)caption {

UIBarButtonItem *backButton =[[UIBarButtonItem alloc] init];

backButton.title= caption;
self.navigationItem.backBarButtonItem = backButton;
[backButton release];

}-(void)setRightButtonCaption:(NSString *)caption selectot:(SEL)selector {

  UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] init];
rightButton.title = caption;

rightButton.target= self;

[rightButton setAction:selector];

self.navigationItem.rightBarButtonItem= rightButton;

[rightButton release];

}

现在,在任何自定义视图中,都可以通过以下方法实现此基本视图:

@interface LoginView:BaseController {

在某些方法中调用基本方法为:

SEL sel = @选择器(switchToForgotPIN);

[super setRightButtonCaption:@“”忘记了PIN“ selectot:sel];

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.