Skip to content

Latest commit

ย 

History

History
81 lines (64 loc) ยท 2.36 KB

onChange().md

File metadata and controls

81 lines (64 loc) ยท 2.36 KB

onChange(of:perform:)

๊ณต์‹๋ฌธ์„œ : Performs an action when a specified value changes.

Declaration

func onChange<V>(
    of value: V,
    perform action: @escaping (V) -> Void
) -> some View where V : Equatable

Parameters

value

  • ํด๋กœ์ €์˜ ์‹คํ–‰ ์—ฌ๋ถ€๋ฅผ ๊ฒฐ์ •ํ•  ๋•Œ ํ™•์ธํ•  ๊ฐ’.
  • value๋Š” Equatable ํ”„๋กœํ† ์ฝœ์„ ์ค€์ˆ˜ํ•ด์•ผํ•œ๋‹ค.

action

  • ๊ฐ’์ด ๋ณ€๊ฒฝ๋  ๋•Œ ์‹คํ–‰ํ•  ํด๋กœ์ €์ด๋‹ค.
  • ํด๋กœ์ €๋Š” ์—…๋ฐ์ดํŠธ๋œ ๊ฐ’์„ ๋‚˜ํƒ€๋‚ด๋Š” newValue ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ์‚ฌ์šฉ๋œ๋‹ค.

Return Value

์ง€์ •ํ•œ ๊ฐ’์ด ๋ณ€๊ฒฝ๋  ๋•Œ action์„ ์‹คํ–‰ํ•œ ๋ทฐ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

Overview

onChange()๋Š” Environment๊ฐ’์ด๋‚˜ ๋ฐ”์ธ๋”ฉ๋œ ๊ฐ’์ด ๋ณ€๊ฒฝ๋  ๋•Œ ์‹คํ–‰ํ•  ํด๋กœ์ €์ด๋‹ค.

ex) ๋ทฐ๊ฐ€ background๋กœ ์ด๋™ํ•˜๋Š” ๊ฒƒ์„ ๋ฐœ๊ฒฌํ•  ๊ฒฝ์šฐ ์บ์‹œ๋ฅผ ์ง€์šฐ๋Š” ์ฝ”๋“œ

struct ContentView: View {
    @Environment(\.scenePhase) private var scenePhase
    @StateObject private var cache = DataCache()

    var body: some View {
        MyView()
            .onChange(of: scenePhase) { newScenePhase in
                if newScenePhase == .background {
                    cache.empty()
                }
            }
    }
}

onChange()์—์„œ SwiftUI๋Š” ์ƒˆ ๊ฐ’์„ ํด๋กœ์ €์— ์ „๋‹ฌํ•˜๋ฉฐ, ์ด์ „ ๊ฐ’์„ ์บก์ณํ•˜์—ฌ ์ƒˆ ๊ฐ’๊ณผ ๋น„๊ต๋„ ํ•  ์ˆ˜ ์žˆ๋‹ค.

ex) Player View๊ฐ€ ์ด์ „ ๊ฐ’๊ณผ ์ƒˆ ๊ฐ’ ๋ชจ๋‘ ๋ชจ๋ธ์—๊ฒŒ ์ „๋‹ฌํ•˜๋Š” ์ฝ”๋“œ์ด๋‹ค.

struct PlayerView: View {
    var episode: Episode
    @State private var playState: PlayState = .paused

    var body: some View {
        VStack {
            Text(episode.title)
            Text(episode.showTitle)
            PlayButton(playState: $playState)
        }
        .onChange(of: playState) { [playState] newState in
            model.playStateDidChange(from: playState, to: newState)
        }
    }
}

์œ„ ์ฝ”๋“œ์—์„œ playState๋Š” oldValue, newState๋Š” newValue๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋œ๋‹ค.

์ถ”๊ฐ€

  • ํ•„์š”์‹œ UI๋ฅผ ์—…๋ฐ์ดํŠธํ•œ๋‹ค.

  • onChange๋Š” ๋ฉ”์ธ ์Šค๋ ˆ๋“œ์—์„œ ํ˜ธ์ถœ๋œ๋‹ค. -> ๋ฉ”์ธ ์Šค๋ ˆ๋“œ์—์„œ ๊ธด ์ž‘์—…์„ ์‹คํ–‰ ๊ธˆ์ง€.( ex. ์„œ๋ฒ„์™€์˜ ํ†ต์‹ )

  • ๊ฐ’ ๋ณ€๊ฒฝ์— ๋Œ€ํ•œ ์‘๋‹ต์œผ๋กœ ๊ธด ์ž‘์—…์„ ์‹คํ–‰ํ•ด์•ผํ•˜๋Š” ๊ฒฝ์šฐ ๋ฐฑ๊ทธ๋ผ์šด๋“œ ํ๋กœ Dispatchํ•ด์•ผํ•œ๋‹ค.

  • ์ด์ „ ๊ฐ’์„ ์บก์ณํ•œ๋‹ค.


๊ณต์‹๋ฌธ์„œ