91: Flashzilla, part 6

그루두·2024년 8월 19일
0

100 days of SwiftUI

목록 보기
99/108

Project 17, part 6

퀴즈를 통해 알게 된 점

  • The sequenced(before:) modifier lets us create chains of gestures.
  • Timers pause in the background by default
  • Struct initializers can contain closures as parameters. If they are the last property in the struct Swift will enable trailing closure syntax automatically. -> sheet, button처럼 closure로 설정할 수 있는 것들

challenge

  1. When adding a card, the text fields keep their current text. Fix that so that the textfields clear themselves after a card is added.
  2. If you drag a card to the right but not far enough to remove it, then release, you see it turn red as it slides back to the center. Why does this happen and how can you fix it? (Tip: think about the way we set offset back to 0 immediately, even though the card hasn’t animated yet. You might solve this with a ternary within a ternary, but a custom modifier will be cleaner.)
  3. For a harder challenge: when the users gets an answer wrong, add that card back into the array so the user can try it again. Doing this successfully means rethinking the ForEach loop, because relying on simple integers isn’t enough – your cards need to be uniquely identifiable.

Try upgrading our loading and saving code in two ways:

  1. Make it use an alternative approach to saving data, e.g. documents JSON rather than UserDefaults, or SwiftData – this is generally a good idea, so you should get practice with this.
  2. Try to find a way to centralize the loading and saving code for the cards. You might need to experiment a little to find something you like!

solution

1. 새 카드가 추가될 때 textfield 초기화하기

    func addCard() {
        // ...
        newPrompt = ""
        newAnswer = ""
    }

커밋 링크

2. 카드를 오른쪽으로 swipe하다 놓을 때 빨강색으로 변하는 것 수정하기

확인해보니, offset.width가 0이 되는 순간에 .red로 설정되어 빨강색이 지정됨을 알 수 있다.

                .background(
                    accessibilityDifferentiateWithoutColor
                    ? nil
                    : RoundedRectangle(cornerRadius: 25)
                        .fill(offset.width > 0 ? .green : .red)

그래서 삼항 연산자를 통해 offset이 0일 땐 흰색이 되도록 설정했다.

                .background(
                    accessibilityDifferentiateWithoutColor
                    ? nil
                    : RoundedRectangle(cornerRadius: 25)
                        .fill(offset.width > 0 ? .green : (offset.width < 0 ? .red : .white))
                )

커밋 링크

3. 틀린 카드(왼쪽으로 넘긴 카드)를 다시 카드 스택에 쌓기

CardView에서 왼쪽 swipe를 감지해서 removal 함수에 Bool로 여부를(isCorrect) 넘겼다. 그리고 ContentView에서 removeCard 함수에서 이를 확인하고 isCorrect가 false인 경우 카드 스택(cards)에 추가하도록 했다.
커밋 링크

이 경우엔 아래 사진처럼 cards에선 다시 추가되는 것을 확인할 수 있으나,

아래 동영상처럼 화면에서 카드가 새로 쌓이지 않고 swipe가 적용되지 않음을 확인할 수 있다.

현재 상황에서는 ForEach가 cards 기반이 아니라 index를 기반으로 화면에 나타내는 거라서 의도대로 적용되는 것이 아닌가 모르겠다. 시간을 가지고 cards 기반 ForEach도 만들어 보면서 수정해봐야겠다.

profile
계속 해보자

0개의 댓글

관련 채용 정보