我目前正在构建一个页面来将玩家信息添加到本地数据库中。对于每个输入,我都有一个TextFields集合,它链接到player结构中的元素。
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()
}
}我的玩家结构是
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
}问题是ShirtNumber、身高和体重都是Int值。当我将它们绑定到TextField时,我会看到一个错误,即Cannot convert value of type 'Binding<Int>' to expected argument type 'Binding<String>'。我研究过的关于SwiftUI的所有内容都表明,不可能有一个Int值绑定到它的TextField。
我的问题是,是否有可能创建一个扩展TextField但只允许Int输入并绑定Int变量的新类,就像这样?
struct IntTextField: TextField {
init(_ text: String, binding: Binding<Int>) {
}
}到目前为止,我所能找到的只是this问题中我的部分问题(只接受输入)的答案。我正在寻找一种将此与Binding<Int>相结合的方法。
谢谢你的帮助。
发布于 2021-07-06 10:27:07
试图让它在没有UIKit的情况下工作,因为我试图构建一个小型的macOS应用程序,所以UIKit没有出现,所以找到了一个使用两个变量的解决方案(不是最干净的,而是有效的)。
变量声明:
@State var minutes = 0
@State var minutesString = "0"TextField和Stepper:
HStack {
TextField("minutes", text: self.$minutesString)
.onReceive(Just(self.minutesString)) { newValue in
let filtered = newValue.filter { $0.isNumber }
if filtered != newValue {
self.minutesString = filtered
self.minutes = Int(filtered) ?? -1
}
}
Stepper("minutes", value: $minutes).onChange(of: self.hours) { newValue in
self.minutesString = String(newValue)
}
.labelsHidden()
}这将导致两个变量在写入textField或步骤时都会发生更改,并且不允许输入除数字之外的任何内容。
我对整个迅速的事情有点陌生,所以任何反馈都是非常感谢的。
https://stackoverflow.com/questions/59507471
复制相似问题