使用UIHostingController/SwiftUI创建一个关闭视图的按钮可以通过以下步骤实现:
import SwiftUI
struct ContentView: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
VStack {
Text("Hello, World!")
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("关闭视图")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import UIKit
import SwiftUI
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let contentView = ContentView()
let hostingController = UIHostingController(rootView: contentView)
addChild(hostingController)
view.addSubview(hostingController.view)
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
hostingController.didMove(toParent: self)
}
}
通过以上步骤,你就可以在SwiftUI视图中创建一个关闭按钮,并在点击按钮时关闭当前视图。
领取专属 10元无门槛券
手把手带您无忧上云