LoginSignup
5
6

More than 3 years have passed since last update.

ViewとしてのSwiftUI

Posted at

SwiftUIを今までのXibやStoryboardの代わりとして使うための方法をまとめました。
Playgroundで実行します。
ViewControllerを使わない、SwiftUIとModelだけのアーキテクチャにはまだ慣れないですが、コードレイアウトとしてのSwiftUIはメリットが大きいので、取り入れていきたいです。

登場人物と関係

クラス 説明
MyViewController SwiftUIで作ったViewを表示するためのViewController
ContentView SwiftUI
ContentViewDelegate ボタンをタップした時のdelegate
ViewModel タップ回数の変数を格納するObservableObject

それぞれの主な役割は以下の図です。

SwiftUI+ViewController.jpg

基本的なMVCです。

実装

import UIKit
import PlaygroundSupport
import SwiftUI

class ViewModel: ObservableObject {

    @Published var count: Int = 0

    func increment() {
        count += 1
    }

}

protocol ContentViewDelegate: AnyObject {
    func didTapAdd()
}

struct ContentView: View {

    @ObservedObject var viewModel: ViewModel = .init()

    weak var delegate: ContentViewDelegate?

    var body: some View {
        VStack(spacing: 16) {
            Text("count : \(self.viewModel.count)")
            Button.init("Add") {
                debugPrint("Add")
                self.delegate?.didTapAdd()
            }
        }
    }

}

class MyViewController : UIViewController {

    private var contentView = ContentView.init()

    override func loadView() {
        super.loadView()
        view.backgroundColor = .white

        contentView.delegate = self

        let hostingVC = UIHostingController.init(rootView: contentView)
        hostingVC.view.frame = view.bounds
        view.addSubview(hostingVC.view)

        debugPrint(view.subviews)

        self.view = view

    }
}

extension MyViewController: ContentViewDelegate {

    func didTapAdd() {
        debugPrint("didTapAdd")
        contentView.viewModel.increment()
    }

}

// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

ソース
https://gist.github.com/usk2000/394d70cba327e095f2b8002542721697

画面

5
6
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
5
6