facebook twitter hatena line email

Ios/swift/ナビゲーションバー/コードのみ

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

コードでViewController、ナビゲーションバー生成

  • AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate {
   var window: UIWindow?
   var myNavigationController: UINavigationController?
   func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
       let first: ViewController = ViewController()
       myNavigationController = UINavigationController(rootViewController: first)
       self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
       self.window?.rootViewController = myNavigationController
       self.window?.makeKeyAndVisible()
       return true
   }
  • ViewController.swift
class ViewController: UIViewController {
   var addBtn: UIBarButtonItem!
   override func viewDidLoad() {
       super.viewDidLoad()
       self.title = "Home"
       addBtn = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(ViewController.onClickNavButton))
       self.navigationItem.rightBarButtonItem = addBtn
   }
   func onClickNavButton() {
       let second = SecondViewController()
       self.navigationController?.pushViewController(second, animated: true)
   }
  • SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
   override func viewDidLoad() {
       super.viewDidLoad()
       self.view.backgroundColor = .redColor()
       self.title = "Second"
   }
   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   }
}

参考:http://qiita.com/mochizukikotaro/items/f053495eb130e92e13e8

ViewControllerをstoryboard、ナビゲーションのみをコードで生成

上記コードで以下のようにstoryboardに貼り付けたオブジェクトにアクセスするとエラーになる

@IBOutlet weak var testlabel: UILabel!

以下を

let first: ViewController = ViewController()

以下のように変更し、storyboard上のViewControllerのStoryboardIDを"View"にする

let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) // ここのMainはMain.storyboardのMain
var first : ViewController = storyboard.instantiateViewControllerWithIdentifier("View") as! ViewController