Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Binding<Int> with a TextField SwiftUI

I am currently building a page to add player information to a local database. I have a collection of TextFields for each input which is linked to elements in a player struct.

var body: some View {         VStack {             TextField("First Name", text: $player.FirstName)                 .textFieldStyle(RoundedBorderTextFieldStyle())             TextField("Last Name", text: $player.LastName)                 .textFieldStyle(RoundedBorderTextFieldStyle())             TextField("Email", text: $player.eMail)                 .textFieldStyle(RoundedBorderTextFieldStyle())             TextField("Shirt Number", text: $player.ShirtNumber)                 .textFieldStyle(RoundedBorderTextFieldStyle())             TextField("NickName", text: $player.NickName)             .textFieldStyle(RoundedBorderTextFieldStyle())             TextField("Height", text: $player.Height)                 .textFieldStyle(RoundedBorderTextFieldStyle())             TextField("Weight", text: $player.Weight)                 .textFieldStyle(RoundedBorderTextFieldStyle())              Button(action: {                 submitPlayer(player: self.player)T             }) {                 Text("Submit")             }              Spacer()         }     } 

My player struct is

struct Player: Hashable, Codable, Identifiable {     var id: Int     var FirstName: String     var LastName: String     var NickName: String     var eMail: String     var ShirtNumber: Int     var Height: Int     var Weight: Int } 

The issue is that ShirtNumber, Height, and Weight are all Int values. When I bind them to the TextField I get an error saying Cannot convert value of type 'Binding<Int>' to expected argument type 'Binding<String>'. Everything I have looked into about SwiftUI says it's impossible to have a TextField with an Int value bound to it.

My question is, would it be possible to create a new class that extends TextField but allows for only Int inputs and that binds an Int variable, something like this?

struct IntTextField: TextField {      init(_ text: String, binding: Binding<Int>) {      } }  

So far all I have been able to find is an answer to part of my question (accepting only Int input) from this question. I am looking for a way to combine this with the Binding<Int>.

Thanks for the help.

like image 639
Bernard Avatar asked Dec 28 '19 01:12

Bernard


1 Answers

Actually , you can binding manyTypes with TextField:

      @State var weight: Int = 0       var body: some View {          Group{        Text("\(weight)")        TextField("Weight", value: $weight, formatter: NumberFormatter())     }} 
like image 62
E.Coms Avatar answered Sep 28 '22 08:09

E.Coms