3

我有 SwiftUI 页面,它正在从 UIKit 视图中导航。我想为此页面设置标题,我正在做的是

// code of UIKit view
let controller = UIHostingController(rootView: SwiftUIView())
controller.title = "title"
MyNavigationManager.present(controller)

有没有办法可以在 SwiftUI 中访问托管控制器?

然后我可以编写类似的代码 self.hostingController?.title = "title"

4

2 回答 2

4

这是一个可能的方法的演示 - 使用外部配置包装类来保存到控制器的弱链接并将其注入到 SwiftUI 视图中(作为替代,也可以使其ObservableObject与其他全局属性和逻辑相结合)。

使用 Xcode 12.5 / iOS 14.5 测试

class Configuration {
    weak var hostingController: UIViewController?    // << wraps reference
}

struct SwiftUIView: View {
    let config: Configuration   // << reference here

    var body: some View {
        Button("Demo") {
            self.config.hostingController?.title = "New Title"
        }
    }
}

let configuration = ExtConfiguration()
let controller = UIHostingController(rootView: SwiftUIView(config: configuration))

// injects here, because `configuration` is a reference !!
configuration.hostingController = controller

controller.title = "title"
MyNavigationManager.present(controller)
于 2021-04-30T13:34:42.460 回答
1

我选择了一个不同的选项 - 子类 NSHostingController 以便它提供自己作为环境变量。

struct SwiftUIView: View {
    @EnvironmentObject var host:HSHostWrapper

    var body: some View {
        Button("Dismiss") {
            host.controller?.dismiss(self)
        }
    }
}

let controller = HSHostingController(rootView: SwiftUIView())

这是通过以下 HSHostingController 实现的(在HSSwiftUI 包中可用)

import Foundation
import SwiftUI


#if os(iOS) || os(tvOS)
    import UIKit
    public typealias ViewController = UIViewController
    public typealias HostingController = UIHostingController
#elseif os(OSX)
    import AppKit
    public typealias ViewController = NSViewController
    public typealias HostingController = NSHostingController
#endif

public class HSHostWrapper:ObservableObject {
    public weak var controller:ViewController?
}


/// allows root view (and children) to access the hosting controller by adding
/// @EnvironmentObject var host:HSHostWrapper
/// then e.g. host.controller?.dismiss()
public class HSHostingController<Content>:HostingController<ModifiedContent<Content,SwiftUI._EnvironmentKeyWritingModifier<HSHostWrapper?>>> where Content : View {
    
    public init(rootView:Content) {
        let container = HSHostWrapper()
        let modified = rootView.environmentObject(container) as! ModifiedContent<Content, _EnvironmentKeyWritingModifier<HSHostWrapper?>>
        super.init(rootView: modified)
        container.controller = self
    }
  
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
于 2021-08-17T13:45:03.897 回答