CS193p 2021
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Help
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# 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](https://youtu.be/ayQl_F_uMS4?t=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](https://youtu.be/ayQl_F_uMS4?t=143) @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?](https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-state-property-wrapper) ## [05:02](https://youtu.be/ayQl_F_uMS4?t=302) access control ```swift= 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](https://youtu.be/ayQl_F_uMS4?t=672) open, public, interal #### [11:37](https://youtu.be/ayQl_F_uMS4?t=697) 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](https://youtu.be/ayQl_F_uMS4?t=1568) computed properties `indexOfTheOneAndOnlyFaceUpCard` 這筆資料事實上已經被記錄在 cards: [Card] 裡面。 如果不注意,之後可能會導致兩邊資料不同步,這樣不好。看我們把它改成 computed properties。 ```swift= // Before private var indexOfTheOneAndOnlyFaceUpCard: Int? ``` ```swift= // 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](https://youtu.be/ayQl_F_uMS4?t=2035) functional programming * this is real functional programming here. * we're passing a funciton to another function to get the thing we want. ```swift= // 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 } } } ``` ```swift= // After get { cards.indices.filter({ cards[$0].isFaceUp }).oneAndOnly } set { cards.indices.forEach { cards[$0].isFaceUp = ($0 == newValue) } ``` > 使用高階函數陳述,即 functional programming? (保留) ## [46:33](https://youtu.be/ayQl_F_uMS4?t=2793) Property Observer 強調這東西跟 computed property 不一樣 ```swift= var isFaceUp: Bool { willSet { if newValue { startUsingBonusTime() } else { stopUsingBonusTime() } } } ``` ## [50:03](https://youtu.be/ayQl_F_uMS4?t=3003) Layout 1. `Container View`s "offer" space to the `View`s inside them 2. `View`s then choose what size they want to be 3. `Container View`s then **position** the `View`s inside of them 4. (and based on that, `Container View`s choose their own size as per #2 above) (白話) 1. 提供廣場讓小朋友自由成長 2. 小朋友有各自的理由決定他的大小 3. 已經知道小朋友的大小,所以可以排列這些小朋友,在廣場上怎麼個對齊法 4. 如果這個廣場是在某個更大的世界內,那麼廣場就需要決定自己的大小(重複第二步) #### [51:38](https://youtu.be/ayQl_F_uMS4?t=3098) 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](https://youtu.be/ayQl_F_uMS4?t=3297) layoutPriority() ![](https://i.imgur.com/m8Zixbb.png) [ Doc - `layoutpriority(_:)`](https://developer.apple.com/documentation/swiftui/view/layoutpriority(_:)) - default priority of 0 - Raising a view’s layout priority encourages the higher priority view to shrink later ```swift= HStack { Text("This is a moderately long string.") Spacer() Text("This is a higher priority string.") .layoutPriority(1) } ``` ![](https://i.imgur.com/0qbvw8k.png) #### [56:02](https://youtu.be/ayQl_F_uMS4?t=3362) alignment ```swift= VStack(alignment: .leading) {...} HStack(alignment: .firstTextBaseline) {...} ``` 用 leading, trailing 是因為 right-to-left 語言也可以受惠。 #### [57:29](https://youtu.be/ayQl_F_uMS4?t=3449) 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](https://youtu.be/ayQl_F_uMS4?t=3564) ZStack ![](https://i.imgur.com/8nQmORR.jpg) #### [1:01:22](https://youtu.be/ayQl_F_uMS4?t=3682) View.modifiers ![](https://i.imgur.com/5YPBJQg.jpg) ![](https://i.imgur.com/eCyNvlj.jpg) #### [1:06:38](https://youtu.be/ayQl_F_uMS4?t=3998) GeometryReader ![](https://i.imgur.com/oZDZjA9.png) #### [1:08:37](https://youtu.be/ayQl_F_uMS4?t=4117) safe area ```swift= ZStack { ... }.edgesIgnoringSafeArea([.top]) // draw in "safe area" on top edge ``` ## [1:10:08](https://youtu.be/ayQl_F_uMS4?t=4208) back to the demo use `GeometryReader` to calculate the font size of the text on the card view ```swift= 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](https://youtu.be/ayQl_F_uMS4?t=4882) @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 `let`s ```swift= @ViewBuilder func front(of card: Card) -> some View { let shape = RoundedRectangle(cornerRadius: 20) shape shape.stroke() Text(card.content) } ```

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully