StoryBoardを使わずにXibで画面を作る
1ViewController,1StoryBoardで開発していると言うことをよく聞きますが、私のプロジェクトは1ViewController,1Xibで開発しています。
せっかくなのでXibでの開発方法をまとめます。
新規viewControllerにxibを作成する場合
新規で作成する場合は簡単です。Also Create Xib fileにチェックを入れてviewControllerを作成します。

今回はTestViewControllerと言う名前でviewControllerを作成したのでTestViewController.xibと言うファイルが自動生成されているはずです。
このxibファイルにauto layoutでレイアウトの設定を行い画面を作っていきます。
既存のviewControllerにxibを作成する場合
xibファイルの生成
File > New > FileからViewを選択して作成します。

この時作成する名前はViewControllerの名前と合わせてください。XibとViewControllerの名前が一致していないと後々面倒になります。
今回はHogeViewControllerというViewControllerのxibを用意するのでHogeViewController.xibと言う名前でxibファイルを作成します。

xibとviewControllerの紐付け
既存のViewControllerにXibを追加する際は紐付けが必要になります。
まずFile’s Ownerを設定します対応させたいViewControllerを❸の部分に書きます。

次にFile’s OwnerとViewの紐付けを行います。
Control+クリックでFile’s OwnerとViewの接続を行います。

接続できているかどうかはViewを右クリックで確認することができます。
接続できているとこんな感じになるはずです。

これで既存のviewControllerにxibを作成する手順が完了すあとは新規でXibを追加した時同様にレイアウトを組むことができます。
遷移時のinitializer
デフォルトのinitializerを使用する場合はXcodeがよしなにやってくれるので問題ありませんが、自作のinitializerを作成する場合はどのXibを使うのか指定が必要になります。
例としてTestViewControllerのinitializerを作成してみました。nibNameの部分にxibファイルの名前が入ります。
XibファイルとViewControllerの名前を統一した方が良いのはこのためです。
required initはStory boardから遷移した時に呼ばれるinitializerです。ないとXcodeに怒られますがStory Boardから遷移は使わないので初期状態のままで大丈夫です。
init() {
super.init(nibName: String(describing: TestViewController.self), bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}