Try   HackMD

CS193P - Lecture 5: Properties Layout @ViewBuilder - 86 mins

  • Demo code at cs193p.stanford.edu
  • summary
    • @State
    • Access Control
    • Computed Properties
    • Extensions
    • Property Observers
    • Layout
    • @ViewBuilder

00: 42 property wrappers

  • @ObservedObject, @State, these things we called property wrappers.
  • Views are supposed to be stateless.
  • we're supposed to be drawing what's in the model.
  • They don't need any state of their own.
  • so having then be read-only like this is great.

02:23 @State

we kick off an animation, and we want to track the end point of the animation. But animation clearly a very temporary thing going on inside the View. @State is for that sort of storage.

it replaces your var in your View with a pointer to some space in memory. that space in memory actually lives for as long as the lifetime of your View, not the life time of your View struct. When we use the phrase "lifetime of your View", we mean the lifetime of its body on screen. So as long as the body of your View is onscreen somehow, the thing your @State points to will stay around and when the View struct itself is getting desroyed and rebuild, it's always getting re-pointed back to that. So you can rely on your @State staying the same and living as long as your body is on screen somewhere.

  • When we put @State before a property, we effectively move its storage out from our struct and into shared storage managed by SwiftUI.
  • @State should be used with simple struct types such as String, Int, and arrays, and generally shouldn’t be shared with other views.
  • If you want to share values across views, you should probably use @ObservedObject or @EnvironmentObject instead
    (HackingWithSwift) What is the @State property wrapper?

05:02 access control

class EmojiMemoryGame: ObservableObject { @Published private var model: MemoryGame<String> = createMemoryGame() var cards: Array<MemoryGame<String>.Card> { model.cards } }

what access control is all about: protecting your internal data structures from other code looking at it or modifying it.

11:12 open, public, interal

11:37 Xcode Refactor Tool

  • open difinition (option + click)
  • fold function
  • rename things throughout entire app
  • typealias
// EmojiMemoryGameView
viewModel -> game
// EmojiMemoryGame 
typealias Card = MemoryGame<String>.Card

26:08 computed properties

indexOfTheOneAndOnlyFaceUpCard 這筆資料事實上已經被記錄在 cards: [Card] 裡面。
如果不注意,之後可能會導致兩邊資料不同步,這樣不好。看我們把它改成 computed properties。

// Before private var indexOfTheOneAndOnlyFaceUpCard: Int?
// After private var indexOfTheOneAndOnlyFaceUpCard: Int? { get { cards.indices.filter { cards[$0].isFaceUp == true }.oneAndOnly } set { cards.indices.forEach { cards[$0].isFaceUp = ($0 == newValue) } } }

33:55 functional programming

  • this is real functional programming here.
  • we're passing a funciton to another function to get the thing we want.
// Before get { var faceUpCardIndices = [Int]() for index in cards.indices { if cards[index].isFaceUp { faceUpCardIndices.append(index) } } if faceUpCardIndices.count == 1 { return faceUpCardIndices.first } else { return nil } } set { for index in cards.indices { if index != newValue { cards[index].isFaceUp = false } else { cards[index].isFaceUp = true } } }
// After get { cards.indices.filter({ cards[$0].isFaceUp }).oneAndOnly } set { cards.indices.forEach { cards[$0].isFaceUp = ($0 == newValue) }

使用高階函數陳述,即 functional programming? (保留)

46:33 Property Observer

強調這東西跟 computed property 不一樣

var isFaceUp: Bool { willSet { if newValue { startUsingBonusTime() } else { stopUsingBonusTime() } } }

50:03 Layout

  1. Container Views "offer" space to the Views inside them
  2. Views then choose what size they want to be
  3. Container Views then position the Views inside of them
  4. (and based on that, Container Views choose their own size as per #2 above)

(白話)

  1. 提供廣場讓小朋友自由成長
  2. 小朋友有各自的理由決定他的大小
  3. 已經知道小朋友的大小,所以可以排列這些小朋友,在廣場上怎麼個對齊法
  4. 如果這個廣場是在某個更大的世界內,那麼廣場就需要決定自己的大小(重複第二步)

51:38 HStack & VStack

  • inflexible: Image (it wants to be a fixed size)
  • slightly more flexible: Text (always wants to size to exactly fit its text)
  • very flexible: RoundedRectangle (always uses any space offered)

Text 為什麼是 slightly more flexible?

  • 從 inflexible view 開始,漸漸往 very flexible view 決定各自的大小
  • After the Views inside the stack choose their own sizes, the stack sizes itself to fit them
  • If any of the Views in the stack are "very flexible", then the stack will also be "very flexible"

Spacer(minLength: CGFloat) 這個東西沒事就會吃掉幾乎所有的空間

Divider() 這個東西就只會盡可能只吃掉最小的空間

54:57 layoutPriority()

 Doc - layoutpriority(_:)

  • default priority of 0
  • Raising a view’s layout priority encourages the higher priority view to shrink later
HStack { Text("This is a moderately long string.") Spacer() Text("This is a higher priority string.") .layoutPriority(1) }

56:02 alignment

VStack(alignment: .leading) {...} HStack(alignment: .firstTextBaseline) {...}

用 leading, trailing 是因為 right-to-left 語言也可以受惠。

57:29 Lazy

LazyHStack and LazyVStack

  • don't build any of their Views that are not visible
    • 如果有 9990 個 cell 在螢幕外,就可以先不理他們

ScrollView

  • ScrollView takes all the space offered to it
  • The views inside it are sized to fit along the axis your scrolling on.

59:24 ZStack

1:01:22 View.modifiers

1:06:38 GeometryReader

1:08:37 safe area

ZStack { ... }.edgesIgnoringSafeArea([.top]) // draw in "safe area" on top edge

1:10:08 back to the demo

use GeometryReader to calculate the font size of the text on the card view

struct CardView: View { let card: EmojiMemoryGame.Card var body: some View { GeometryReader { geometry in if card.isFaceUp { Text(card.content).font(font(in: geometry.size)) } ... } } } private func font(in size: CGSize) -> Font { Font.system(size: min(size.height, size.width) * DrawingConstants.fontScale) } }

除此之外,本章改動的內容多是 access control, naming, Swift Type Inference 等與 SwiftUI 不直接相關,故省略。

1:21:22 @ViewBuilder

  • any func or computed var can be marked with @ViewBuilder
  • the contents of a @ViewBuilder is just a list of Views
  • if-else statements can be used to choose Views to include in the list
  • can alse have local lets
@ViewBuilder func front(of card: Card) -> some View { let shape = RoundedRectangle(cornerRadius: 20) shape shape.stroke() Text(card.content) }