Notes for SwiftUI and Combine Programming (1)
I start reading onevcat new book SwiftUI and Combine Programming (a great book to learning SwiftUI if you can read Chinese). I decided to put all the interest parts and notes in here.
First things First
We always need to import
the dependency first
import SwiftUI
import Combine
Layout all the views in the body
var body: some View {
/// Layout your view here
}
some View
is a new concept introduced in Swift 5.1, which called Opaque
Types. Maybe someday I will write a more detail post for opaque types, in
short, opaque types kind like protocol
but more powerful.
Enable Canvas in Xcode
You can preview the UI layouts using Canvas, which is convincing by
PreviewProvider
. As long as your swift file have a struct
confirm it, you
will able to work with SwiftUI and preview changes using Canvas support (Xcode 11+ and OS X
10.15 + Only)
struct MyView_Previews: PreviewProvider {
static var previews: some View {
MyView()
}
}
Canvas is not fast
At least not fast as I wish, we still need to build the whole project first, then it starts working as we hope. But sometimes I found I may easier break the UI, then Xcode start not happy anymore, showing this on canvas

In this case, we have to resume the canvas which rebuilds the project again 😢
Preview with multiple devices
Canvas support preview with all devices, so we can work on different size of screens:
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
Group {
ContentView()
ContentView().previewDevice("iPhone SE")
ContentView().previewDevice("iPad Air 2")
}
}
}
After some loading 😫, we should see something like this:
