【问题标题】:SwiftUI Control flow build elementsSwiftUI 控制流构建元素
【发布时间】:2020-03-02 05:15:25
【问题描述】:

我最近开始使用 SwiftUI,虽然它也有一些好东西,但到目前为止我很失望。尤其是它使得创建大而杂乱的代码变得非常容易,并让我想起了各种 XML(或 HTML)结构。 无论如何,我遇到了以下问题,我无法在任何地方找到解决方案。 我需要在运行时绘制某些矩形(或形状),将其视为以某种方式生成水平条形图。因为矩形的数量是动态的,所以我需要在一个方法中生成它,但是到目前为止我尝试过的任何方法都会从编译器收到错误。

每当我尝试使用某种流控制(例如“for”或“while”)来生成以下元素时:

struct ContentView: View {

或:

 var body: some View {

我要么得到:

Function declares an opaque return type, but has no return statements in its body from which to infer an underlying type

Closure containing control flow statement cannot be used with function builder 'ViewBuilder'

使用 SwiftUI 绘制动态元素有什么更好的方法。 我已经在动态列表上看到了大量示例,尽管 Apple 在第一天就已经涵盖了这些示例,但没有任何关于自定义元素或者如果您想创建动态设置数量的 HStack 或 Vstack 的内容,那不是格式化为列表。

谢谢!

【问题讨论】:

    标签: swift xcode conditional-statements swiftui


    【解决方案1】:

    ViewBuilders are special things and you cannot use certain control flow statements in them.

    您可以调用单独的 (private) 函数来执行适当的控制流并生成适当的视图。

    请参阅 John Sundell 撰写的关于支持 SwiftUI 的 Swift 5.1 功能的博文:https://www.swiftbysundell.com/articles/the-swift-51-features-that-power-swiftuis-api/

    【讨论】:

      猜你喜欢
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多