-
-
Save byaruhaf/fab346013a7a84e8c03330a9a631877c to your computer and use it in GitHub Desktop.
SwiftUI TextField which only accepts integers and binds to an Int? instead of a String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
private class IntegerTextFieldValue: ObservableObject { | |
@Published var value = "" { | |
didSet { | |
let numbersOnly = value.filter { $0.isNumber } | |
if value != numbersOnly { | |
value = numbersOnly | |
} | |
} | |
} | |
} | |
struct IntegerTextField: View { | |
@Binding var value: Int? | |
@StateObject private var fieldValue = IntegerTextFieldValue() | |
var placeholder = "" | |
var body: some View { | |
TextField(placeholder, text: $fieldValue.value) | |
.keyboardType(.numberPad) | |
.onChange(of: fieldValue.value) { value = Int($0) } | |
.onAppear { | |
if let value = value { | |
fieldValue.value = "\(value)" | |
} | |
} | |
} | |
} | |
struct NumericTextField_Previews: PreviewProvider { | |
static var previews: some View { | |
IntegerTextField(value: .constant(17)) | |
.textFieldStyle(RoundedBorderTextFieldStyle()) | |
.padding() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment