Created
April 9, 2021 23:35
-
-
Save rhysm94/8459318a15f6cb9f01cdaeee2261db7f to your computer and use it in GitHub Desktop.
Example of a UIViewRepresentable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import PlaygroundSupport | |
import SwiftUI | |
import UIKit | |
final class LabelledImage: UIView { | |
let label = UILabel() | |
let image = UIImageView() | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
configureView() | |
} | |
required init?(coder: NSCoder) { | |
fatalError() | |
} | |
private func configureView() { | |
backgroundColor = .systemBackground | |
addSubview(label) | |
addSubview(image) | |
translatesAutoresizingMaskIntoConstraints = false | |
label.translatesAutoresizingMaskIntoConstraints = false | |
label.textAlignment = .center | |
let labelConstraints = [ | |
label.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor), | |
label.leadingAnchor.constraint(greaterThanOrEqualTo: safeAreaLayoutGuide.leadingAnchor), | |
label.trailingAnchor.constraint(greaterThanOrEqualTo: safeAreaLayoutGuide.trailingAnchor), | |
label.centerXAnchor.constraint(equalTo: safeAreaLayoutGuide.centerXAnchor) | |
] | |
image.translatesAutoresizingMaskIntoConstraints = false | |
let imageConstraints = [ | |
image.topAnchor.constraint(equalTo: label.bottomAnchor), | |
image.centerXAnchor.constraint(equalTo: label.centerXAnchor), | |
image.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor) | |
] | |
NSLayoutConstraint.activate(labelConstraints + imageConstraints) | |
} | |
} | |
struct LabelledImageView: UIViewRepresentable { | |
@Binding var text: String | |
@Binding var image: UIImage? | |
func makeUIView(context: Context) -> LabelledImage { | |
LabelledImage() | |
} | |
func updateUIView(_ uiView: LabelledImage, context: Context) { | |
uiView.label.text = text | |
uiView.image.image = image | |
} | |
} | |
struct MainView: View { | |
var body: some View { | |
VStack { | |
Text("Hello, from SwiftUI") | |
.padding() | |
LabelledImageView(text: .constant("Hello, from UIKit"), image: .constant(UIImage(systemName: "star"))) | |
} | |
} | |
} | |
PlaygroundPage.current.setLiveView(MainView()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment