Language/Swift

SwiftUI를 이용한 값 증가나 감소 컨트롤하기 (Stepper)

IFLA 2022. 11. 18. 08:00

 

사용자가 값을 증가시키거나 감소시키는 걸 제어할 수 있도록 하는 게 Stepper 컨트롤이 도와준다.

  • 지정한 범위 내에서 작동된다.
  • Stepper의 기능한 값 범위에서 특정 양만큼 단계적으로 수행한다.

 

기본 코드

import SwiftUI

struct ContentView: View {
    @State private var amount = 5.0

    var body: some View {
        Stepper(value: $amount, in: 0...50, step: 2) {
                Text("Amount: \(amount)")
        }
        .padding()
    }
}

 

실행화면

 

 

Stepper 메소드

  • onIncrement : 증가 버튼을 클릭할 경우 발생
  • onDecrement : 감소 버튼을 클릭할 경우 발생
struct ContentView: View {
    @State private var value = 0.0

    func increment() {
        value += 1

        if value >= 10 { value = 0 }
    }

    func decrement() {
        value -= 1

        if value < 0 { value = 10 }
    }

    var body: some View {
        Stepper(onIncrement: increment, onDecrement: decrement) {
                Text("Amount: \(amount)")
        }
        .padding()
    }
}

 


개발자 Document

Apple Developer Documentation