【问题标题】:Adding Navigation Bar programmatically iOS以编程方式添加导航栏 iOS
【发布时间】:2014-01-30 05:43:54
【问题描述】:

我正在尝试制作一个带有导航栏(后退按钮、标题等)和标签栏(底部的工具栏)的应用程序。我正在使用子视图,所以我不必担心状态栏、导航栏、标签栏高度等。但我认为这给我带来了麻烦,因为我似乎无法弄清楚如何设置导航栏和标签栏.

这就是我所拥有的。我做错了什么?

AppDelegate.h

(default for single view app)

AppDelegate.m

(default for single view app)

ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (strong, nonatomic) UIView *contentSubview;
@end

ViewController.m

#import "ViewController.h"
@interface ViewController ()
@end

@implementation ViewController
- (void)loadView{}
- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor greenColor];
    self.contentSubview = [[UIView alloc] init];
    self.contentSubview.backgroundColor = [UIColor orangeColor];
    [view addSubview:self.contentSubview];
    self.view = view;
}

- (void)viewWillLayoutSubviews
    {
    [super viewWillLayoutSubviews];
    self.contentSubview.frame = CGRectMake(
                                       0,
                                       self.topLayoutGuide.length,
                                       CGRectGetWidth(self.view.frame),
                                       CGRectGetHeight(self.view.frame)-self.topLayoutGuide.length-self.bottomLayoutGuide.length
                                       );
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

【问题讨论】:

  • 这段代码与添加导航栏或工具栏有什么关系?您是想添加一个导航栏和工具栏,还是想要一个导航控制器?你想完成什么?
  • 我想这就是我感到困惑的地方。我想添加一个导航栏和工具栏。但我正在使用子视图,所以我不确定是否必须做一些不同的事情。

标签: ios objective-c iphone swift xcode


【解决方案1】:
-(void)ViewDidLoad
{
 UINavigationBar* navbar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];

UINavigationItem* navItem = [[UINavigationItem alloc] initWithTitle:@"karthik"];
// [navbar setBarTintColor:[UIColor lightGrayColor]];
UIBarButtonItem* cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(onTapCancel:)];
navItem.leftBarButtonItem = cancelBtn;

UIBarButtonItem* doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(onTapDone:)];
navItem.rightBarButtonItem = doneBtn;

[navbar setItems:@[navItem]];
[self.view addSubview:navbar];
}


-(void)onTapDone:(UIBarButtonItem*)item{

}

-(void)onTapCancel:(UIBarButtonItem*)item{

}

Swift3

let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height:44)) // Offset by 20 pixels vertically to take the status bar into account

    navigationBar.backgroundColor = UIColor.white


    // Create a navigation item with a title
    let navigationItem = UINavigationItem()
    navigationItem.title = "Title"

    // Create left and right button for navigation item
     let leftButton =  UIBarButtonItem(title: "Save", style:   .plain, target: self, action: #selector(ViewController.btn_clicked(_:)))

    let rightButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: nil)

    // Create two buttons for the navigation item
    navigationItem.leftBarButtonItem = leftButton
    navigationItem.rightBarButtonItem = rightButton

    // Assign the navigation item to the navigation bar
    navigationBar.items = [navigationItem]

    // Make the navigation bar a subview of the current view controller
    self.view.addSubview(navigationBar)




func btn_clicked(_ sender: UIBarButtonItem) {
    // Do something
}

斯威夫特

 // Create the navigation bar
    let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 44)) // Offset by 20 pixels vertically to take the status bar into account

    navigationBar.backgroundColor = UIColor.whiteColor()
    navigationBar.delegate = self;

    // Create a navigation item with a title
    let navigationItem = UINavigationItem()
    navigationItem.title = "Title"

    // Create left and right button for navigation item
    let leftButton =  UIBarButtonItem(title: "Save", style:   UIBarButtonItemStyle.Plain, target: self, action: "btn_clicked:")
    let rightButton = UIBarButtonItem(title: "Right", style: UIBarButtonItemStyle.Plain, target: self, action: nil)

    // Create two buttons for the navigation item
    navigationItem.leftBarButtonItem = leftButton
    navigationItem.rightBarButtonItem = rightButton

    // Assign the navigation item to the navigation bar
    navigationBar.items = [navigationItem]

    // Make the navigation bar a subview of the current view controller
    self.view.addSubview(navigationBar)


  func btn_clicked(sender: UIBarButtonItem) {
  // Do something
 }

【讨论】:

  • 我让它工作并显示一个导航栏。然而,设置标题和项目被证明是困难的。
  • 我也想设置一个带图标的标签栏。
  • @boxmatic 你是如何设置标题和项目的?
【解决方案2】:

xib方法:

来自here的教程

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

    // Create the PlainViewController (and give it a title)
    PlainViewController *plainView = [[PlainViewController alloc] initWithNibName:@"PlainViewController" bundle:nil];
    [plainView setTitle:@"PlainView"];

    // Create the NavRootView controller (and give it a title)
    NavRootView *navRoot = [[NavRootView alloc] initWithNibName:@"NavRootView" bundle:nil];
    [navRoot setTitle:@"NavRoot"];

    // Create our navigation controller using our NavRootView as it's root view
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:navRoot];

    // Make an array containing our plain view controller and our navigation controller
    NSArray *viewArray = [NSArray arrayWithObjects:plainView, navController, nil];

    // Release the views and nav controller
    [plainView release];
    [navRoot release];
    [navController release];

    // Create our tab bar controller
    UITabBarController *tabbarController = [[UITabBarController alloc] init];

    // Tell the tab bar controller to use our array of views
    [tabbarController setViewControllers:viewArray];

    // Finally, add the tabbar controller as a subview of the app window
    [window addSubview:[tabbarController view]];

    [self.window makeKeyAndVisible];
    return YES;
}

只有代码:

howto-implement-uinavigationcontroller-uitabbarcontroller-programmatically

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    /* Initialize window view */
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    /* Initialize tab bar controller, add tabs controllers */
    self.tabBarController = [[UITabBarController alloc] init];
    self.tabBarController.viewControllers = [self initializeTabBarItems];
    self.window.rootViewController = self.tabBarController;

    [self.window makeKeyAndVisible];
    return (YES);
}

- (NSArray *)initializeTabBarItems
{
    NSArray * retval;

    /* Initialize view controllers */
    ViewController1 * viewController1 = [[ViewController1 alloc] init];
    ViewController2 * viewController2 = [[ViewController2 alloc] init];
    ViewController3 * viewController3 = [[ViewController3 alloc] init];
    ViewController4 * viewController4 = [[ViewController4 alloc] init];
    ViewController5 * viewController5 = [[ViewController5 alloc] init];

    /* Initialize navigation controllers */
    UINavigationController * navigationController1 = [[UINavigationController alloc] initWithRootViewController:viewController1];
    UINavigationController * navigationController2 = [[UINavigationController alloc] initWithRootViewController:viewController2];
    UINavigationController * navigationController3 = [[UINavigationController alloc] initWithRootViewController:viewController3];
    UINavigationController * navigationController4 = [[UINavigationController alloc] initWithRootViewController:viewController4];
    UINavigationController * navigationController5 = [[UINavigationController alloc] initWithRootViewController:viewController5];



    /* Stuff Navigation Controllers into return value */
    retval = [NSArray arrayWithObjects:viewController1,viewController2,viewController3,viewController4,viewController5,nil];



    return (retval);
}

故事板:

storyboards-tutorial-in-ios-7

【讨论】:

  • 这个教程有点老了。我尝试使用唯一的代码版本,但无法使其工作。
【解决方案3】:

在 Objective-C 中

UINavigationBar* navigationbar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, UIApplication.sharedApplication.statusBarFrame.size.height, self.view.frame.size.width, 50)];
UINavigationItem* navigationItem = [[UINavigationItem alloc] initWithTitle:@"Title"];
[navigationbar setItems:@[navigationItem]];
[self.view addSubview:navigationbar];

在斯威夫特中

let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.size.height, width: view.frame.size.width, height:44))
    let navigationItem = UINavigationItem()
    navigationItem.title = "Title"
    navigationBar.items = [navigationItem]
    self.view.addSubview(navigationBar)

【讨论】:

    【解决方案4】:

    斯威夫特 5.

    上下文:这是一个用于编辑用户生物信息的视图控制器。

    import UIKit
    
    class EditBioController: UIViewController {
    
        // What you need are these two classes. One is a navigation bar,
        // and the other will hold the items that are in the navigation bar.
        private var navigationBar: UINavigationBar!
        private var customNavigationItem: UINavigationItem!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Create a navigation bar with the width of the view, and the standard height of 44.
            navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 44))
            
            // Initialize the UINavigationItem class. The name is a bit confusing, because as you'll see -
            // we add multiple items to the one 'UINavigationItem.'
            customNavigationItem = UINavigationItem()
            customNavigationItem.title = "Edit Bio"
            
            let leftBarButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(selectorX))
            customNavigationItem.leftBarButtonItem = leftBarButton
            
            let rightBarButton = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(selectorX))
            customNavigationItem.rightBarButtonItem = rightBarButton
            
            // Add the items to the navigation bar.
            navigationBar.items = [customNavigationItem]
            // Add the navigation bar to the view.
            self.view.addSubview(navigationBar)
            
            
        }
        
        @objc func selectorX() {
            
        }
        
    }
    

    这是产生的结果:

    【讨论】:

      【解决方案5】:

      Swift 版本,在 viewDidLoad 中添加:

      var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "doneButton:")
      navigationItem.rightBarButtonItem = doneButton
      

      这在你的视图控制器类中

      func doneButton(sender: UIBarButtonItem) {
          println(111)
      }
      

      【讨论】:

      • 问题是关于添加导航栏而不是如何为栏按钮项添加处理程序
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多