In Swift UI I am struggling to find a solution to editing Int16
and Double
values primarily linked to CoreData entities.
The SwiftUI TextField("key", value: $int16, format: .number)
crashes whenever a number too large for the Int16 type is typed in, understandibly.
What I would like my textfield to do is
- Bind to a
Int16?
andString
- When there is a value within the textfield the
appending
string is appended to the end but it not selectable or editable in anyway - Any leading 0s should be removed and never shown (unless the .allowZero option is being used)
- AutoFill/Pasting should only be allowed if they’re numbers (if thats not possible then not at all)
- When all values within the string are removed the textfield should be blank, the appending string should disappear and the Int16 binding should become nil. (This allows for the view to validate the Int16 as if there is an acceptable value Int16 will not be nil)
At the moment I have created an enum which allows you to select additional rules for the TextField, such as allow negative values and allow 0. These have not been integrated yet.
My current problems are to do with pasting/autofill.
- Autocomplete is able to enter values that I do not want such as letters and then I am unable to remove them, this should not be possible it should either filter out all characters that aren’t numbers or ignore the new string entirely
- Managing the cursor is proving difficult for me, when selecting a range of values for example the
234
in the Int1612345
and replace it with another value, say1
. The cursor appears here 115| instead of here 11|5 where I believe it would be expected. - the textfield doesn’t scale with dynamic type font sizes
I am inexperienced with the UIViewRepresentable and UITextField and so there may be other problems visible to those who know it well. All help is greatly appreciated, in my current project this is proving to be quite the hurdle for general safety.
Below is an example of the code I have so far.
struct Int16TextField: UIViewRepresentable {
let titleKey: String
@Binding var text: String
@Binding var int16: Int16?
let appending: String
let options: Set<Int16TextFieldOptions>
init(_ titleKey: String, text: Binding<String>, int16: Binding<Int16?>, options: Set<Int16TextFieldOptions> = [], appending: String = "") {
let x = NSLocalizedString(titleKey, comment: "")
self.titleKey = x
self._text = text
self._int16 = int16
self.appending = appending
self.options = options
}
func makeUIView(context: Context) -> UITextField {
let textField = getTextField()
textField.delegate = context.coordinator
return textField
}
//SwiftUI to UIKit
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = text
}
private func getTextField() -> UITextField{
let textField = UITextField()
let placeHolder: NSAttributedString = NSAttributedString(string: titleKey, attributes: [:])
textField.attributedPlaceholder = placeHolder
textField.keyboardType = .numberPad
return textField
}
//UIKit to SwiftUI
func makeCoordinator() -> Coordinator {
return Coordinator(text: $text, int16: $int16, options: options, appending: appending)
}
class Coordinator: NSObject, UITextFieldDelegate {
@Binding var text: String
@Binding var int16: Int16?
let appending: String
let options: Set<Int16TextFieldOptions>
init(text: Binding<String>, int16: Binding<Int16?>, options: Set<Int16TextFieldOptions>, appending: String) {
self._text = text
self._int16 = int16
self.appending = appending
self.options = options
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var oldValue = textField.text ?? ""
var newValue = string
print(oldValue.debugDescription, newValue.debugDescription)
if oldValue.hasSuffix(appending){
oldValue = String(oldValue.dropLast(appending.count))
}
if newValue.isEmpty && oldValue.count == 1 {
int16 = nil
textField.text = ""
text = ""
return false
}
// Ensure only numbers are allowed
let allowedCharacters = CharacterSet.decimalDigits
let characterSet = CharacterSet(charactersIn: newValue)
guard allowedCharacters.isSuperset(of: characterSet) else {
return false
}
//place new digit(s) wherever the cursor is range.location == cursour position
guard let textRange = Range(range, in: oldValue) else {
return false
}
//If cursor is at the beginning and we're adding only 0's, dont!
if range.location == 0{
if newValue.hasPrefix("0"){
while newValue.hasPrefix("0") {
newValue.removeFirst()
}
if newValue.isEmpty{
return false
}
}
}
var updatedText = oldValue.replacingCharacters(in: textRange, with: newValue)
//Trim leading 0's
while updatedText.hasPrefix("0") {
updatedText.removeFirst()
}
//ensure Int16 conformance
if updatedText != ""{
guard let newInt16 = Int16(updatedText), newInt16 <= Int16.max else {
return false
}
int16 = newInt16
}
else {
int16 = nil
}
updatedText += appending
if updatedText == appending {
int16 = nil
textField.text = ""
text = ""
return false
}
textField.text = updatedText
text = updatedText
// Calculate the new cursor position
let newCursorPosition: Int = (string.count == 0 ? range.location : range.location + string.count - range.length)
if let newPosition = textField.position(from: textField.beginningOfDocument, offset: newCursorPosition) {
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
}
return false
}
func textFieldDidChangeSelection(_ textField: UITextField) {
if !appending.isEmpty {
guard let selectedRange = textField.selectedTextRange else { return }
let cursorPosition = textField.offset(from: textField.beginningOfDocument, to: selectedRange.start)
let textLength = textField.text?.count ?? 0
if selectedRange.start == textField.beginningOfDocument && selectedRange.end == textField.endOfDocument {
let newPosition = textField.position(from: textField.endOfDocument, offset: -appending.count)
if let newPosition = newPosition{
textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: newPosition)
}
}
for decrement in 0...(appending.count - 1) {
if cursorPosition == (textLength - decrement) {
let newPosition = textField.position(from: textField.endOfDocument, offset: -appending.count)
if let newPosition = newPosition {
textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition)
}
break
}
}
}
}
}
}
And here is a ContentView and the Int16TextFieldOptions
enum to be used in previews.
struct ContentView: View {
@State var text: String = ""
@State var int16: Int16?
@State var appending: String = "cm"
@State var options: Set<Int16TextFieldOptions> = [.allowMinus]
func testInt16() -> String {
guard let new = int16 else {return "nil"}
return new.description
}
var body: some View {
VStack {
Form{
HStack{
Text("String:")
Spacer()
Text(text.debugDescription)
}
HStack{
Text("Int16:")
Spacer()
Text(testInt16())
}
Int16TextField(options.rangeString(), text: $text, int16: $int16, options: options, appending: appending)
}
}
}
}
enum Int16TextFieldOptions{
case allowMinus, allowZero
}
extension Set<Int16TextFieldOptions> {
func rangeString() -> String {
var x = "Range: "
if self.contains(.allowZero){
if self.contains(.allowMinus){
//both
x += "-32768...32767"
}
else {
//just zero
x += "0...32767"
}
}
else if self.contains(.allowMinus){
//minus
x += "-32768...-1, 1...32767"
}
else {
x += "1...32767"
}
guard x != "Range: " else { fatalError() }
return x
}
}
Any help would be greatly appreciated as I feel I have come to a dead end on this problem.
Thank you