LoginSignup
14
17

More than 5 years have passed since last update.

【swift3】storyboardでナビゲーションバーを作る

Last updated at Posted at 2016-11-20
  • 環境
  • 実装(16'11/20追記分)
  • 実装
  • 余談

環境

  • Mac OS: 10.12.1
  • Xcode: 8.1
  • swift: 3.0.1

【Swift1系】【Swift2系】Swiftで開発している人必見!ターミナルでSwiftのバージョンを確認する方法

実装(16'11/20追記分)

ShinokiRyoseiさんから
Navigation Controllerの使用を薦めて頂いたので、
その手順もまとめます。(ありがとうございますm(_ _)m)

完成図
nav3.gif

こちらが手順のgif
nav4-iloveimg-compressed.gif

  1. ViewControllerを選択
  2. Editor > Embed in > Navigation Controller
  3. Navigation Controllerが作られる
  4. ViewControllerをドラッグし、作る
  5. Bar Button Itemを1つ目のViewに追加
  6. Attributes Inspector > Bar Item > Title をNextに変更
  7. Ctrlを押しながら6で追加したitemを、2つ目のViewにドラッグ
  8. Segueでshowを選択
  9. navigation bar部分を選択
  10. Attributes Inspector の TitleにFirst View、Back ButtonにBackを記入 ※ 移動先の「戻るボタン」に表示されるテキスト
  11. 2つ目のViewにNavigation itemを追加
  12. TitleにSecond Viewと記入

これで完成!

実装

storyboard上ですることまとめ(少し早いですが...)
makeNav.gif

  1. ViewControllerをドラッグする(FirstViewControllerとする)
  2. 1を繰り返す(SecondViewControllerとする)
  3. Navigation Barを各Controllerにドラッグする
  4. Bar Button Itemを各Controllerにドラッグする
  5. FirstViewControllerに置いたボタンをCtrlを押しながらSecondViewControllerにドラッグ
  6. モーダルが表示されるので、showをクリック
  7. SecondViewControllerに置いたボタンをCtrlを押しながら、SecondViewControllerの一番右の丸(Exit)にドラッグ
  8. モーダルが表示されるのでクリック

gifに載っていないこと

  • デフォルトで作られるViewControllerをFirstViewControllerにリネームする

右クリック > Refactor > Rename ではリファクタリングができない。(ObjCのみ)
XcodeでSwiftのリファクタリングができないから、renameの代わりにターミナルのコマンドで一括置換してみた

  • File > new > File... > swift.fileを選択(名前をSecondViewControllerにする)
  • storyboard > (右側の)show the identity inspector > Custom Classに、FirstViewController, SecondViewControllerをそれぞれ入力
  • 各Controllerに以下のコードを記述.
FirstViewController.swift
import UIKit

class FirstViewController: UIViewController {
    // SecondViewControllerから戻るために必要
    @IBAction func back(segue:UIStoryboardSegue) {}

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
SecondViewController.swift
import UIKit

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

余談

  • import Fundation

import FoundationにはいくつかのAPIが含まれている。
import UIKitimport Cocoaimport Foundationの内容は含まれている。らしい。
what is differant 'import Cocoa' and 'import Foundation' in Xcode's Playground

  • Segue

swift Segueの種類について

14
17
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
17