如何从 swiftui 视图调用 uikit 视图控制器方法 [英] How to call a uikit viewcontroller method from swiftui view

查看:42
本文介绍了如何从 swiftui 视图调用 uikit 视图控制器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找遍了这个问题的答案,但似乎找不到.如何从 swiftUI 调用 viewController 方法(例如,在单击按钮时)?

I have looked all over for the answer to this question and can't seem to find it. How can I call a viewController method from swiftUI (e.g. on a button click)?

我有一个如下所示的视图控制器:

I have a viewcontroller that looks like this:

import Player

class PlayerViewController: UIViewController {
    var player = Player()
    func play() {
        self.player.play()
    }
}

我有一个看起来像这样的包装器:

And I have a wrapper that looks like this:

import SwiftUI
import AVFoundation

struct ProjectEditorPlayerBridge: UIViewControllerRepresentable {

    func makeUIViewController(context: Context) -> PlayerViewController {
        let player = PlayerViewController()
        return player
    }
    
    func updateUIViewController(_ uiViewController: PlayerViewController, context: Context) {
    }
    
    typealias UIViewControllerType = PlayerViewController
}

我希望能够在 swiftUI 中使用按钮操作并调用一次 viewController play 方法.我已经看到建议在包装器上设置状态/绑定并在 updateUIViewController 中调用方法的答案,但是当我这样做时,我看到它被多次调用,而不仅仅是一次.

I want to be able to use a button action in swiftUI and call the viewController play method once. I have seen answers that suggest setting state/binding on the wrapper and calling the method in updateUIViewController, but when I do this I see it gets called multiple times, not just once.

推荐答案

这里有一种可能的基于协议/配置器的方法,它允许直接使用从代码简单性和可读性来看更合适的操作.

Here is possible protocol/configurator based approach, which allows to use actions directly that looks more appropriate from code simplicity and readability.

protocol Player { // use protocol to hide implementation
    func play()
}

class PlayerViewController: UIViewController, Player {
    var player = Player()
    func play() {
        self.player.play()
    }
}

struct ProjectEditorPlayerBridge: UIViewControllerRepresentable {
    var configurator: ((Player) -> Void)? // callback

    func makeUIViewController(context: Context) -> PlayerViewController {
        let player = PlayerViewController()

        // callback to provide active component to caller
        configurator?(player)

        return player
    }

    func updateUIViewController(_ uiViewController: PlayerViewController, context: Context) {
    }

    typealias UIViewControllerType = PlayerViewController
}

struct DemoPlayerView: View {
    @State private var player: Player?     // always have current player

    var body: some View {
        VStack {
            ProjectEditorPlayerBridge { self.player = $0 }  // << here !!

            // use player action directly !!
            Button("Play", action: player?.play ?? {})
        }
    }
}

这篇关于如何从 swiftui 视图调用 uikit 视图控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆