blog icon indicating copy to clipboard operation
blog copied to clipboard

How to make TextField Stepper in SwiftUI

Open onmyway133 opened this issue 1 year ago • 0 comments

Use HStack with TextField and a little extension

extension Binding where Value == Int {
    var toString: Binding<String> {
        Binding<String>(
            get: {
                "\(wrappedValue)"
            },
            set: {
                wrappedValue = Int($0) ?? 0
            }
        )
    }
}

struct TextFieldStepper: View {
    @Binding var value: Int
    
    var body: some View {
        HStack(spacing: 0) {
            TextField("", text: $value.toString)
                .textFieldStyle(.roundedBorder)
                .frame(width: 50)
            Stepper("", value: $value)
        }
    }
}

onmyway133 avatar Jun 20 '23 07:06 onmyway133