Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying an empty view in SwiftUI

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?

like image 563
Max Desiatov Avatar asked Apr 02 '20 09:04

Max Desiatov


People also ask

What is empty view?

Treatment of Constipation Emty Oral Solution is a laxative that treats constipation by drawing water into the bowels thereby making stools softer and easier to pass. This medicine takes a couple of days to work (up to 3 days). Take it as instructed even it appears not to be working.

How do I hide a view in SwiftUI?

Use an opacity(_:) modifier with a value of 0 so that the layout accounts for the error message whether or not it's visible. You can also use this strategy for removing a view that doesn't affect other views' placement, like a view inside an overlay(alignment:content:) modifier.

How do I set views in SwiftUI?

Use SwiftUI Views From Other FrameworksChoose File > New > File, select iOS as the platform, select the “SwiftUI View” template, and click Next. Name the new file MapView. swift and click Create. Add an import statement for MapKit .


1 Answers

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.

like image 192
Procrastin8 Avatar answered Sep 19 '22 08:09

Procrastin8