0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SwiftUIからUIKitのUILabelを表示する。

Last updated at Posted at 2021-02-11

はじめに

SwiftUIからUIKitの利用を理解する為の最初の一歩として
最低限の実装方法を記載したものです。

スクリーンショット 2021-02-14 8.34.56.png

環境

macOS Big Sur 11.1
XCode 12.4
Swift 5

実装

SwiftUI上でUIKitのUILabelを表示するだけのソースコードです。
値の受け渡し、コーディネーターは使っていません。

[1].UIViewRepresentable
 SwiftUIでUIKitのViewを使用するために必要。
 [2], [3]の実装は必須。
[2].makeUIViewメソッド
 SwiftUI側に返却するUILabelのインスタンスを返却する。
[3].updateUIViewメソッド
 (今回は何もしない。)

ContentView.swift
import SwiftUI

struct ContentView: View {
    
    var body: some View {
        ZStack {
            // SwiftUI -------------
            VStack {
                Text("HelloWorld (SwiftUI)")
                    .frame(maxWidth: .infinity)
                Spacer()
            }
            .background(Color.blue)

            // UIKit ---------------
            HelloWorldUIKitLabel()
                .frame(height: 100)
        }
    }
}

struct HelloWorldUIKitLabel:UIViewRepresentable { // [1]

    func makeUIView(context: Context) -> UILabel { // [2]
        let label = UILabel()
        label.text = "HelloWorld (UIKit)"
        label.backgroundColor = UIColor.red
        label.textAlignment = NSTextAlignment.center
        return label
    }

    // 最低限の事しかやらないので、update処理は特に何もしません。
    func updateUIView(_ uiView: UILabel, context: Context) { // [3]
    }
}

次回は値の受け渡しなど
を記事にする予定

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?