Displaying an empty view in SwiftUI

十年热恋 提交于 2021-01-21 07:02:59

问题


In SwiftUI there's frequently a need to display an "empty" view based on some condition, e.g.:

struct OptionalText: View {
  let text: String?

  var body: some View {
    guard let text = text else { return }

    return Text(text) 
  }
}

Unfortunately, this doesn't compile since the body of guard has to return some view, that is an "empty" view when text is nil. How should this example be rewritten so that it compiles and renders an "empty" view when text is nil?


回答1:


You have to return something. If there is some condition where you want to display nothing, "display" an...EmptyView ;)

var body: some View {
    Group {
        if text != nil {
            Text(text!)
        } else {
            EmptyView()
        }
    }
}

The SwiftUI DSL will require you to wrap the if/else in a Group and the DSL has no guard/if let nomenclature.




回答2:


As of Xcode 12 beta 2 the Group view is no longer needed and if let declarations are supported, so the resulting body can be a bit more succint:

var body: some View {
    if let text = text {
        Text(text)
    } else {
        EmptyView()
    }
}



回答3:


You can use the @ViewBuilder. Then you don't even need an EmptyView:

@ViewBuilder
var body: some View {
    if let text = text {
        Text(text)
    }
}

Note than you don't return anything, with a @ViewBuilder you just build your view.



来源:https://stackoverflow.com/questions/60988527/displaying-an-empty-view-in-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!