来源: https://www.avanderlee.com/swiftui/integrating-swiftui-with-uikit/

在HWS中学到了怎么在SwiftUI中使用UIKit,那么快来学一下怎么使用SwiftUI吧

在SwiftUI中定义了一个Controller名字叫UIHostingController,介绍就是A UIKit view controller that manages a SwiftUI view hierarchy.

那就直接拿来用就行,使用Push或者Present都是可行的。

这里先创建了一个SwiftUIView

1
2
3
4
5
6
func presentSwiftUIView() {
let swiftUIView = SwiftUIView()
let hostingController = UIHostingController(rootView: swiftUIView)
// present(hostingController, animated: true, completion: nil)
navigationController?.pushViewController(hostingController, animated: true)
}

Dec-01-2020 22-14-31功能也是完整的。但是如果要直接在当前的Controller上显示呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func addSwiftUIView() {
let swiftUIView = SwiftUIView()
let hostingController = UIHostingController(rootView: swiftUIView)

/// Add as a child of the current view controller.
addChild(hostingController)

/// Add the SwiftUI view to the view controller view hierarchy.
view.addSubview(hostingController.view)

/// Setup the constraints to update the SwiftUI view boundaries.
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
hostingController.view.leftAnchor.constraint(equalTo: view.leftAnchor),
view.bottomAnchor.constraint(equalTo: hostingController.view.bottomAnchor),
view.rightAnchor.constraint(equalTo: hostingController.view.rightAnchor)
]

NSLayoutConstraint.activate(constraints)

/// Notify the hosting controller that it has been moved to the current view controller.
hostingController.didMove(toParent: self)
}

Dec-01-2020 22-14-31还可以改成泛型的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
extension UIViewController {

/// Add a SwiftUI `View` as a child of the input `UIView`.
/// - Parameters:
/// - swiftUIView: The SwiftUI `View` to add as a child.
/// - view: The `UIView` instance to which the view should be added.
func addSubSwiftUIView<Content>(_ swiftUIView: Content, to view: UIView) where Content : View {
let hostingController = UIHostingController(rootView: swiftUIView)

/// Add as a child of the current view controller.
addChild(hostingController)

/// Add the SwiftUI view to the view controller view hierarchy.
view.addSubview(hostingController.view)

/// Setup the contraints to update the SwiftUI view boundaries.
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
hostingController.view.leftAnchor.constraint(equalTo: view.leftAnchor),
view.bottomAnchor.constraint(equalTo: hostingController.view.bottomAnchor),
view.rightAnchor.constraint(equalTo: hostingController.view.rightAnchor)
]

NSLayoutConstraint.activate(constraints)

/// Notify the hosting controller that it has been moved to the current view controller.
hostingController.didMove(toParent: self)
}
}