boxmatic boxmatic - 6 months ago 1055
Swift Question

Adding Navigation Bar programmatically iOS

I am trying to make an App with a Navigation Bar (Back button, title, etc) and a Tab Bar (Toolbar on the bottom). I am using subviews so I don't have to worry about the status bar, navigation bar, tab bar heights, etc. But I think it's causing me trouble because I can't seem to figure out how to setup the Nav and Tab Bars.

Here is what I have. What am I doing wrong?

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

Answer
-(void)ViewDidLoad
{
 UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
 //do something like background color, title, etc you self
[self.view addSubview:navbar];
}

Swift

 // 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
 }