カテゴリー
iOS Swift

StoryboardなしでUIViewアプリ作成を始める

ステップ1: main Storyboardを削除

ステップ2: Main Interface にある”Main”を削除

ステップ3: Info.plistのUISceneStoryboardFileとMainの記述を削除

ステップ4: SceneDelegateのfunc scene() を以下のように記述

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
  guard let windowScene = (scene as? UIWindowScene) else { return }
  window = UIWindow(frame: windowScene.coordinateSpace.bounds)
  window?.windowScene = windowScene
  window?.rootViewController = ViewController()
  window?.makeKeyAndVisible()
}

ステップ5: ViewControllerにコードを記述開始

import UIKit

class ViewController: UIViewController {
  let bannerHeight: CGFloat = 100.0	
  var viewWidth: CGFloat {
    view.bounds.width
  }
	
  var viewHeight: CGFloat{
    view.bounds.height
  }
	
  var topInset: CGFloat {
    view.safeAreaInsets.top
  }
	
  var bottomInset: CGFloat {
    view.safeAreaInsets.bottom
  }
	
  var appAreaHeight: CGFloat {
    viewHeight - topInset - bottomInset - bannerHeight
  }	
	
  lazy var first: UIView = {
    let view = UIView()
    view.backgroundColor = .red
    return view
  }()
	
  lazy var second: UIView = {
    let view = UIView()
    view.backgroundColor = .blue
    return view
  }()
	
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
		
    view.addSubview(first)
    view.addSubview(second)
  }
	
  override func viewWillLayoutSubviews() {
    print("topInset: \(topInset)")
    print("bottomInset: \(bottomInset)")
    first.frame = CGRect(x: 0, y: topInset + bannerHeight, width: viewWidth, height: appAreaHeight/2)
    second.frame = CGRect(x: 0, y: topInset + bannerHeight + appAreaHeight/2, width: viewWidth, height: appAreaHeight/2)
  }
}