Lec04_01 (MVVC&SwiftUI)
Lec04_01 (MVVC&SwiftUI)
MVVM
SwiftUI Layout
Acknowledgement:
For online CIS193 course slides published by Stanford
University
Course Updates
■ HelloSwiftUI-Env.zip App Demo updated with
@State
@StateObject
@ObservedObject
@EnvironmentObject
Application Icon
■ Assignment 01 uploaded, due 02/03/2024
Question Of the Day – Password:
Model View
UI Independent
Data + Logic
“The Truth”
MVVM
Model View
Model View
ViewModel
s
nge
a Binds View to Model
ch
es Interpreter
tic
no
Model View
Model View
Model View
Model View
Model View
■ No inheritance ■ Inheritance
■Examples …
(Int, Int) -> // takes two Ints and returns a Bool
Bool (Double)-> // takes a Double and returns nothing
Array<String> // takes no arguments and returns an Array of Strings
() -> Void
() -> Void // takes no arguments and returns nothing (this is a common one)
All of the above are just types. No different than Bool or View or Array<Int>. All are
types.
var foo: (Double) -> Void // foo’s type: “function that takes a Double, returns nothing”
func doSomething(what: () -> Bool) // what’s type: “function, takes nothing, returns Bool”
Functions as
T ypes
Functions are types
Example …
var operation: (Double) -> Double
This is a var called operation.
It is of type “function that takes a Double and returns a Double”.
https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-
stateobject-property-wrapper
SwiftUI Property Wrapper
@StateObject
o To share a StateObject in other views, declare the variable
with @ObservedObject wrapper
Button(action: {
}) {
Text("Play")
}.padding(.bottom)
VStack(content: {
Button(action: {
}) {
Text("Solve")
}
Divider().padding(.bottom)
Text("Played # time(s).");
})
})
}
QuizApp -- QuizModel
import Foundation // Notice we not importing swiftui anymore
// Computed variable
var question: String {
get {
if let n1 = self.num1, let n2 = self.num2 {
return "\(n1) + \(n2)"
} else {
return "Expression"
}
}
}
…………………………………
QuizApp -- Model View
import SwiftUI
Button(action: {
quizViewModel.nextQuestion()
}) {
Text(quizViewModel.playButtonText)
}.padding(.bottom)
…………………………..
QuizApp -- Application Icon
QuizApp -- Application Icon
Questions?
More SwiftUI App
2. Create and Combining Views