LoginSignup
1
3

More than 3 years have passed since last update.

Storyboardを使わずにコードベースでプロジェクトを作成する方法

Posted at

はじめに

iOSアプリを複数人で開発する際、Storyboardを使用すると、ソースコードに意図せぬ差分が出やすく管理がめんどくさい・・・。
だったらUIKitじゃなくてSwiftUI使いましょう

ということで、Storyboardを使わずにコードベースで開発する方法をまとめます。

なお、iOS13以降とそれ以前では設定の方法が大きく異なります。
今記事では、iOS14での設定方法をまとめます。

バージョン情報

Xcode 12.3
Swift 5.3.2

プロジェクト作成

1.Xcodeを起動してプロジェクトを作成

通常時と同様の手順でプロジェクトを作成します。

  1. [Create a new Xcode project]
  2. [Single View App]を選択して[Next]
  3. 任意のプロジェクト名を入力
  4. プロジェクト設定
    1. Interface --> Storyboard
    2. Life Cycle --> UIKit
    3. Language --> Swift
  5. プロジェクトを保存

2.Storyboardの削除

上記の手順で作成したプロジェクトからStoryboardを消していきます

  1. Main.Storyboardを削除。

  2. Info.plistの項目[Storyboard Name]を -ボタンで削除
    説明1

  3. [プロジェクト]>TARGETS>ProjectName>General>Development Info>Main Interfaceを空白にする。
    説明2

  4. SceneDelegate.swiftに初期画面情報を設定

以下のように編集。

SceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

        if let windowScene = scene as? UIWindowScene{
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = ViewController.init()
            self.window = window
            window.makeKeyAndVisible()
        }
    }

説明3

3.ビルド

  1. ViewController.swiftを以下のように編集
ViewController.swift
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .red

        let titleLabel: UILabel = {
            let view = UILabel.init()
            view.text = "はろーわーるど★"
            view.textColor = .yellow
            view.translatesAutoresizingMaskIntoConstraints = false
            return view
        }()

        view.addSubview(titleLabel)

        NSLayoutConstraint.activate([
            titleLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0),
            titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0)
        ])
    }


}

説明4

目に悪そうな色ですが、意図通りです。
説明5

おわりに

今回は、iOS14での、Storyboardを使用しないプロジェクトの作成〜ビルドまでをまとめました。
コードでAutoLayoutを使用する場合は、以下のコードでAutoresizingを無効にする必要があリますのでお気をつけください。

ViewController.swift
view.translatesAutoresizingMaskIntoConstraints = false
1
3
0

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
1
3