Codementor Events

SwiftUI - Simple State Management

Published Jun 04, 2019Last updated Oct 18, 2019

Learn about swiftUI :
https://developer.apple.com/xcode/swiftui/
https://developer.apple.com/tutorials/swiftui/

Let's do some code:

In order to use SwiftUI, we need to download XCode 11.
https://developer.apple.com/services-account/download?path=/WWDC_2019/Xcode_11_Beta/Xcode_11_Beta.xip

Steps:

  1. Create simple 'SingleView Application' using xcode 11.
  2. Make sure to check 'use SwiftUI'.
  3. In ContentView.swift, use below code.
import SwiftUI

struct ContentView : View {
    
    @State var counter:Int = 0;
    
    var body: some View {
        VStack {
            HStack {
                Text("You counter value: ")
                    .padding(5)
                Text(String(counter))
                    .font(.largeTitle)
                    .color(.red)
                }.padding(20)
            
            HStack {
                Button(action: {
                    self.counter -= 1
                },
                       label: {
                        Text("Decrease(-)")
                })
                Spacer()
                Button(action: {
                    self.counter += 1
                },
                       label: {
                        Text("Increase(+)")
                })
            }
        }
        .padding(20)
    }
}

Here, When you declare a state, SwiftUI stores it for you and manages the state’s connections to its view. When the state updates, the view invalidates its appearance and updates itself.

That's all 😃

You can also look into Android Jetpack Compose:
Experiment with Android Jetpack Compose

Discover and read more posts from Sunil Mishra
get started
post commentsBe the first to share your opinion
Rene Amerongen van
5 years ago

What about using the counter in another struct anotherView: View {}?

Show more replies