【发布时间】:2019-12-02 16:32:24
【问题描述】:
在下面的代码中,我试图弄清楚如何使用SwiftUI 按钮执行savePhoto 函数。这实际上是我试图解决的问题的简化版本,但仍然无法弄清楚。我在ContentView 中创建的按钮是我想象的解决问题的方法,但由于 SwiftUI 结构,我似乎找不到解决方法。
这是我的 SwiftUI 视图:
struct ContentView: View {
var body: some View {
ZStack{
AnotherControllerView()
Button(action: { AnotherControllerView.savePhoto() }){
Text("Save Photo")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
还有我的集成 UIViewController:
import Foundation
import SwiftUI
import UIKit
struct AnotherControllerView : UIViewControllerRepresentable {
typealias UIViewControllerType = AnotherController
func makeCoordinator() -> AnotherControllerView.Coordinator {
Coordinator(self)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<AnotherControllerView>) -> AnotherController {
return AnotherController()
}
func updateUIViewController(_ uiViewController: AnotherController, context: UIViewControllerRepresentableContext<AnotherControllerView>) {
}
class Coordinator : NSObject {
var parent : AnotherControllerView
init(_ viewController : AnotherControllerView){
self.parent = viewController
}
}
}
class AnotherController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.blue
}
func savePhoto(){
let alert = UIAlertController(title: "Save Photo to Camera Roll", message: "Would you like to save your drawing to the camera roll?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Save", style: .default, handler: someHandler))
self.present(alert, animated: true)
}
func someHandler(alert: UIAlertAction!) {
print("Handler executed")
}
}
【问题讨论】: