How to print() to Xcode console in SwiftUI?

You can easily add a print statement anywhere in a function builder by simply storing its return value in a wildcard, effectively ignoring it: let _ = print(“hi!”) No setup or other verbosity needed! Why does this work while a regular print() doesn’t? The way SwiftUI’s @ViewBuilder (and result builders in general) is that they … Read more

SwiftUI Repaint View Components on Device Rotation

Here‘s an idiomatic SwiftUI implementation based on a notification publisher: struct ContentView: View { @State var orientation = UIDevice.current.orientation let orientationChanged = NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification) .makeConnectable() .autoconnect() var body: some View { Group { if orientation.isLandscape { Text(“LANDSCAPE”) } else { Text(“PORTRAIT”) } }.onReceive(orientationChanged) { _ in self.orientation = UIDevice.current.orientation } } } The output of … Read more

SwiftUI @State and .sheet() ios13 vs ios14

Your code have expectation of view update/creation order, but in general it is undefined (and probably changed in iOS 14). There is explicit way to pass information inside sheet – use different sheet creator, ie. .sheet(item:… Here is working reliable example. Tested with Xcode 12 / iOS 14 struct ContentView: View { @State private var … Read more

SwiftUI Picker onChange or equivalent?

Deployment target of iOS 14 or newer Apple has provided a built in onChange extension to View, which can be used like this: struct MyPicker: View { @State private var favoriteColor = 0 var body: some View { Picker(selection: $favoriteColor, label: Text(“Color”)) { Text(“Red”).tag(0) Text(“Green”).tag(1) } .onChange(of: favoriteColor) { tag in print(“Color tag: \(tag)”) } … Read more

Activity indicator in SwiftUI

As of Xcode 12 beta (iOS 14), a new view called ProgressView is available to developers, and that can display both determinate and indeterminate progress. Its style defaults to CircularProgressViewStyle, which is exactly what we’re looking for. var body: some View { VStack { ProgressView() // and if you want to be explicit / future-proof… … Read more

SwiftUI: Switch .sheet on enum, does not work

With some very small alterations to your code, you can use sheet(item:) for this, which prevents this problem: //MARK: main view: struct ContentView: View { //construct enum to decide which sheet to present: enum ActiveSheet : String, Identifiable { // <— note that it’s now Identifiable case sheetA, sheetB var id: String { return self.rawValue … Read more