1

In SwiftUI, whenever I have a TextField inside a TabView, when I use a bluetooth barcode scanner, the Textfield never gets the correct value from the scanner, it always skips numbers. Sometimes it skips 50% of the barcode, sometimes just 1 or 2 numbers. This happens only when the TextField is inside a Tabview.

I never thought I would get stuck on something like this to be honest, maybe I am missing something very simple?

Here is a testcode:


import SwiftUI

struct Testview: View {
    @State private var searchProductText = ""
    @FocusState var productFieldIsFocused: Bool
    
    var body: some View {
        TabView{
            HStack {
                TextField("", text: $searchProductText)
                    .focused($productFieldIsFocused)
                    .opacity(0)
                    .onSubmit {
                        print(searchProductText)
                        searchProductText = ""
                        productFieldIsFocused = true
                    }
            }.onAppear{
                productFieldIsFocused = true
            }
        }
    }
}

struct Testview_Previews: PreviewProvider {
    static var previews: some View {
        Testview()
    }
}


Axxi
  • 193
  • 1
  • 10
  • Just noticed now that if i remove the "Hstack", the textfield works fine. I have no idea what is causing this tbh, would love some help here. – Axxi Feb 02 '23 at 13:47

1 Answers1

0

I don't know, if this is an intended behavior of SwiftUI, but when you use a @State variable in this structure, the TextField will be redrawn. Since your scanner probably sends the inputs very quickly, the TextField could miss some characters.

In case you really need the HStack, you could try to move your state variable to an ObservableObject.

I found this out, when my cursor always jumped to the end of a TextField whenever I typed a character. This is how I solved it and it should help in your case as well:

class TextViewModel: ObservableObject {
    @Published var txt = ""
}

struct ContentView: View {
    
    @ObservedObject private var viewModel = TextViewModel()
    
    var body: some View {
        TabView {
            VStack {
                TextField("Text", text: $viewModel.txt)
            }
            .padding()
            .tabItem {
                Text("My Tab")
            }
        }
    }
}
FelixSFD
  • 6,052
  • 10
  • 43
  • 117