LoginSignup
3
1

More than 1 year has passed since last update.

Storyboardを使わないコードのみでのプロジェクト作成

Last updated at Posted at 2023-03-12

はじめに

最近UIKitを学び始めた初心者です。
同じ初心者、初学者の方を対象にしてます。また、自分のメモ、備忘録です。

Xcode Version 14.0.1で実行してます。
この記事のサンプルプロジェクト

できるもの

ストーリーボード使わず簡単なラベルを表示
スクリーンショット 2023-03-12 14.34.07.png

Main.storyboard消す

プロジェクトからMain.storyboardを削除します。さよなら!
スクリーンショット 2023-03-12 12.20.28.png

Main storyboard file base nameを削除

TARGETSのinfoのCustom iOS Target Propertiesの → Main storyboard file base nameを削除
スクリーンショット 2023-03-12 12.23.26.png

Storyboard Nameを削除

TARGETSのinfoのCustom iOS Target PropertiesのApplication Scene Manifest → Scene Configuration→ Application SessionRole →Item 0(default Configuration)→Storyboard Nameを削除
スクリーンショット 2023-03-12 12.24.51.png

削除した状態

スクリーンショット 2023-03-12 12.53.36.png

SceneDelegate.swiftにコードを追加

スクリーンショット 2023-03-12 16.20.04.png
下記コードに変更してます。

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        //UIwindowsのアンラップ
        guard let scene = (scene as? UIWindowScene) else { return }
        // window生成
        let window = UIWindow(windowScene: scene)
        // ルートビュー指定
        window.rootViewController = ViewController()
        // キーウインドウ指定
        window.makeKeyAndVisible()
        // windowインスタンスが解放されないようにパラメータに代入する
        self.window = window
    }

ViewController.swiftにコード追加

ViewControllerに下記コード追加しラベルを表示します。


import UIKit

class ViewController: UIViewController {
    var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        label = UILabel()
        label.text = "メタモン"
        label.textAlignment = .center
        label.backgroundColor = .systemPink
        // オートレイアウト使用するためfalseにする
        label.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(label)
        // コードでオートレイアウト制約
        NSLayoutConstraint.activate([
            label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            label.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
            label.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
            label.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            
        ])
    }

}

シュミレーター起動

できました!
スクリーンショット 2023-03-12 14.34.07.png

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