UIViewRepresentable TextField that can append a uneditable string and follows other rules

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? and String
  • 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 Int16 12345 and replace it with another value, say 1. 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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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
}
}
}
}
}
}
</code>
<code>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 } } } } } } </code>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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
}
}
</code>
<code>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 } } </code>
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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật