【问题标题】:How to pass SwiftUI View as function parameter?如何将 SwiftUI View 作为函数参数传递?
【发布时间】:2022-02-07 00:21:10
【问题描述】:

我想将 SwiftUI Views 显示为 UIViewController 的子视图。这些视图必须实现一个协议。

我有这个:

protocol ContentViewProtocol : View
{
    var values: [CGFloat] { get }
}

...

import SwiftUI

struct SearchContentView : ContentViewProtocol
{
    var values: [CGFloat] = [0.5, 0.7]

    var body: some View
    {
        VStack
        {
            ...
        }
    }
}

...

func showContent(view: ContentViewProtocol) <=== ERROR
{
    var child = UIHostingController(rootView: view) <=== SAME ERROR

    ...
}

我收到以下错误:Protocol 'ContentViewProtocol' can only be used as a generic constraint because it has Self or associated type requirements

当使用普通的View 作为函数参数类型时,我得到了同样的错误(func showContent(view: View) 也是如此)。

如何防止这种情况发生?

【问题讨论】:

    标签: ios swift swiftui uikit protocols


    【解决方案1】:

    您可以按照错误提示执行操作,并使用ContentViewProtocol 作为通用约束。使showContent 泛型:

    func showContent<V: ContentViewProtocol>(view: V)
    {
        let child = UIHostingController(rootView: view)
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 2013-09-21
      • 2014-06-29
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 2013-12-30
      • 2016-07-23
      • 2021-10-30
      相关资源
      最近更新 更多