ios - 如何通过 SwiftUI 按钮在 UIViewController 中执行函数?

标签 ios swift swiftui

在下面的代码中,我试图找出如何使用 SwiftUI 按钮执行 savePhoto 函数。这实际上是我试图解决的问题的简化版本,但仍然无法弄清楚。我在 ContentView 中创建的按钮是我想象的解决问题的方式,但由于 SwiftUI 结构,我似乎找不到解决方法。

这是我的 SwiftUI View :

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")
    }
}

最佳答案

你好,为了控制 UIViewController,我们需要在 View 和 UIViewControllerRepresentable 之间创建一个绑定(bind) 让我们用代码解释一下: 首先,您需要在 AnotherControllerView

中声明一个用 @Binding 注释的新变量

它会是这样的:

struct AnotherControllerView : UIViewControllerRepresentable {

    @Binding var isShown: Bool
    typealias UIViewControllerType = AnotherController

    func makeCoordinator() -> AnotherControllerView.Coordinator {
        Coordinator()
    }

    func makeUIViewController(context: UIViewControllerRepresentableContext<AnotherControllerView>) -> AnotherController {

        return AnotherController(isShown: $isShown)
    }

    func updateUIViewController(_ controller: AnotherController, context: UIViewControllerRepresentableContext<AnotherControllerView>) {
        if(self.isShown){
            controller.savePhoto()
        }
    }


    class Coordinator : NSObject {

    }
}

因此在 updateUIViewController 中,我们在那里实现逻辑

class AnotherController : UIViewController {

     @Binding var isShown: Bool

    init(isShown: Binding<Bool>) {
        _isShown = isShown
        super.init(nibName: nil, bundle: nil)

    }



    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    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: cancelAlert))
        alert.addAction(UIAlertAction(title: "Save", style: .default, handler: someHandler))
        self.present(alert, animated: true)
    }

    func cancelAlert(alert: UIAlertAction!) {
        self.isShown = false
    }

    func someHandler(alert: UIAlertAction!) {
        print("Handler executed")
    }
}

如果你想捕捉图像,让我告诉你我是如何实现的:

struct CaptureImageView {
    @Binding var isShown: Bool
    @Binding var image: Image?
    var sourceType: UIImagePickerController.SourceType

    func makeCoordinator() -> Coordinator {
        return Coordinator(isShown: $isShown, image: $image)
    }
}

extension CaptureImageView: UIViewControllerRepresentable {
    func makeUIViewController(context: UIViewControllerRepresentableContext<CaptureImageView>) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        picker.sourceType = sourceType
        return picker
    }

    func updateUIViewController(_ uiViewController: UIImagePickerController, context: UIViewControllerRepresentableContext<CaptureImageView>) {

    }

    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
        @Binding var isCoordindatorShown: Bool
        @Binding var imageInCoordinator: Image?

        init(isShown: Binding<Bool>, image: Binding<Image?>) {
            _isCoordindatorShown = isShown
            _imageInCoordinator = image
        }

        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            guard let unwrapImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {return}
            imageInCoordinator = Image(uiImage: unwrapImage)
            isCoordindatorShown = false
        }

        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            isCoordindatorShown = false
        }
    }

}

在正文中我只是调用:

CaptureImageView(isShown: $showCaptureImageView, image: $imageCaptured, sourceType: importSourceType)

关于ios - 如何通过 SwiftUI 按钮在 UIViewController 中执行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143053/

相关文章:

xcode - 在Xcode中插入问题

xcode - Swift 从完成处理程序中显示 View Controller

ios - 在 SwiftUI 中加载异步请求时显示事件指示器

swift - 如何从SwiftUI的另一个 View 中删除列表的项目?

ios - 为什么 EKEventStore().requestFullAccessToEvents() 适用于模拟器,但不适用于真实设备?

ios - 为什么在viewDidLoad中声明的数组在其他方法中使用时得到未使用的变量警告?

ios - 如何处理 UITableView 非单元格区域的点击

ios - 检测 Realm.io 数据库是否需要迁移——如果需要,销毁它

ios - 如何使用 ios-charts 在一个屏幕上有固定点,然后滑动到下一页?

ios - Swift - 如何以编程方式在它们之间创建带有两个文本和图像的按钮?