Created
November 4, 2023 11:42
-
-
Save calvingit/378fc1d73f8782374f83e0c5a01f1c1f to your computer and use it in GitHub Desktop.
This file contains 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 SwiftUI | |
import UIKit | |
/// 创建一个SwiftUI的容器View,将UIViewControler包含在内,即可预览 | |
/// | |
/// 如果要预览这个ViewController | |
/// | |
/// ```swift | |
/// class ViewController: UIViewController { | |
/// override func viewDidLoad() { | |
/// super.viewDidLoad() | |
/// // Do any additional setup after loading the view. | |
/// } | |
/// } | |
/// ``` | |
/// 使用的时候就可以像这样 | |
/// | |
/// ```swift | |
/// struct ViewController_Previews: PreviewProvider { | |
/// static var previews: some View { | |
/// UIViewControllerPreviewWrapper { | |
/// // 1 | |
/// let storyboard = UIStoryboard(name: "Main", bundle: /// nil) | |
/// guard let viewController = /// storyboard.instantiateInitialViewController() as? /// ViewController | |
/// else { | |
/// fatalError("Cannot load ViewController from Main /// storyboard.") | |
/// } | |
/// | |
/// return viewController | |
/// } | |
/// } | |
/// } | |
/// ``` | |
struct UIViewControllerPreviewWrapper<T: UIViewController>: UIViewControllerRepresentable { | |
// 2 | |
let viewController: T | |
// 3 | |
init(_ viewControllerBuilder: @escaping () -> T) { | |
viewController = viewControllerBuilder() | |
} | |
// MARK: - UIViewControllerRepresentable | |
func makeUIViewController(context: Context) -> T { | |
// 4 | |
return viewController | |
} | |
func updateUIViewController(_ uiViewController: T, context: Context) {} | |
} | |
/// 预览 UIView | |
struct UIViewPreviewWrapper<T: UIView>: UIViewRepresentable { | |
typealias UIViewType = UIView | |
let view: T | |
init(_ viewBuilder: @escaping () -> T) { | |
view = viewBuilder() | |
} | |
func makeUIView(context: Context) -> UIView { | |
return view | |
} | |
func updateUIView(_ uiView: UIView, context: Context) {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment