SwiftUIからUIKitのUILabelを表示する。
はじめに
SwiftUIからUIKitの利用を理解する為の最初の一歩として
最低限の実装方法を記載したものです。
環境
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]
}
}
次回は値の受け渡しなど
を記事にする予定
Author And Source
この問題について(SwiftUIからUIKitのUILabelを表示する。), 我々は、より多くの情報をここで見つけました https://qiita.com/ikaasamay/items/108ac5c211b75a9739d4著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .