SwiftUI 使用 UIKit 控件
由于 SwiftUI
才出来不久,所以有些功能不太好实现,好在苹果提供了接口帮助我们把 UIKit
控件转换为 SwiftUI
使用的控件。
-
UIView
使用UIViewRepresentable
协议
struct AppleIDLoginButton: UIViewRepresentable {
private let type: ASAuthorizationAppleIDButton.ButtonType
private let style: ASAuthorizationAppleIDButton.Style
init(type: ASAuthorizationAppleIDButton.ButtonType = .default,
style: ASAuthorizationAppleIDButton.Style = .white) {
self.type = type
self.style = style
}
func makeUIView(context: UIViewRepresentableContext<AppleIDLoginButton>) -> ASAuthorizationAppleIDButton {
return .init(type: type, style: style)
}
func updateUIView(_ uiView: ASAuthorizationAppleIDButton, context: UIViewRepresentableContext<AppleIDLoginButton>) {
}
}
初始化时会调用 makeUIView
方法,状态更新时会调用updateUIView
方法,具体调用时机可自己测试。
使用:
AppleIDLoginButton(type: .default)
.frame(height: 44)
.onTapGesture {
// code...
}
-
UIViewController
使用UIViewControllerRepresentable
协议
UIViewControllerRepresentable
协议提供方法与UIViewRepresentable
类似。这里使用 SwiftUI 与 Combine 编程 中的代码。
struct SafariView: UIViewControllerRepresentable {
let url: URL
let onFinished: () -> Void
func makeUIViewController(context: UIViewControllerRepresentableContext<SafariView>) -> SFSafariViewController {
let controller = SFSafariViewController(url: url)
controller.delegate = context.coordinator
return controller
}
func updateUIViewController(
_ uiViewController: SFSafariViewController,
context: UIViewControllerRepresentableContext<SafariView>) {
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, SFSafariViewControllerDelegate {
let parent: SafariView
init(_ parent: SafariView) {
self.parent = parent
}
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
parent.onFinished()
}
}
}
makeCoordinator
方法在 UIViewRepresentable
协议中也有。
网友评论