我正在用SwiftUI做实验。我已经有了一个基于UIKit的应用程序工作,我想集成一个SwiftUI视图。我通过使用SwiftUI实现了显示这个UIHostingController视图。
在这个SwiftUI中,我拦截一个按钮动作。在这一行动中,我想:
我在SwiftUI上找不到任何方法来实现这3件事
发布于 2021-12-21 10:49:21
您可以通过多种方式完成此操作:委托、闭包或见鬼,甚至可以使用联合发布服务器。我认为,最简单的开始方式是行动结束。它可能看起来像这样:
struct SwiftUIView: View {
let action: () -> Void
var body: some View {
Button("press me", action: action)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let swiftUIView = SwiftUIView(action: handleButtonPress)
let hostingController = UIHostingController(rootView: swiftUIView)
addChild(hostingController)
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(hostingController.view)
NSLayoutConstraint.activate([
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
}
func handleButtonPress() {
print("TODO: Insert navigation controller logic here")
}
}https://stackoverflow.com/questions/70433674
复制相似问题