L2

26:18
a lot of people when they first started learning SwiftUI,
they think, "oh, that makes this writeable somehow, that now this View is mutable. It's got this variable to be writable."
But that's not true. This View is still immutbale.
It just turn this variable instead of really being a Boolean, it's actually a pointer to some Bollean somewhere else, somewhere in memory.
And that's where the value can change.
But this pointer does not change. It's always pointing to that same little space over there.

45:23 如果是寫這樣的話,點擊 🚆 會有兩個都被響應。

struct ContentView: View { var emojis = ["🚆", "🚆", "🚖", "🛵", "🚀"] var body: some View { HStack { ForEach(emojis, id: \.self) { emoji in CardView(content: emoji) } } .padding(.horizontal) .foregroundColor(.red) } }

59:47 LivePreview 點擊加/減按鈕後有功能,但會 Preview Crash

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

struct ContentView: View { var emojis = [ "🛸", "🚛", "✈️", "🚢", "🚓", "⛵️", "🚁", "🚂", "🚃", "🚀", "🏎", "🚲", "🛵", "🚘" ] @State var emojiCount = 4 var body: some View { VStack { HStack { ForEach(emojis[0..<emojiCount], id: \.self) { emoji in CardView(content: emoji) } } Spacer() HStack { remove Spacer() add } .padding(.horizontal) .font(.largeTitle) } .padding(.horizontal) .foregroundColor(.red) } var remove: some View { Button { emojiCount -= 1 } label: { VStack { Image(systemName: "minus.circle") } } } var add: some View { Button { emojiCount += 1 } label: { Image(systemName: "plus.circle") } } }

1:18:06
a LazyVGrid is lazy about accessing the body vars of all of its Views.
We only get the value of a body var in a LazyVGrid for the Views that actually appear on screen, that scoll on screen.
So this LazyVGrid could scale to having thoudsand of cards, because in general, creating Views is really lightweight.
Usually a View is just a few vars, like isFaceUp and content in our CardView, but accessing a View's body is another story.
That's going to create a whole bunch of other Views, and potentially cause some of their body vars to get accessed.
So there's a lot of infrastructure in SwiftUI to only access a View's body var when absolutely necessary.
This laziness we see in LazyVGrid.

1:22:47

  • GridItem(.fixed)
  • GridItem(.flexable)
  • GridItem(.adaptive)