我想創建一個帶有一些輸入按鈕的自定義文本欄位,單擊這些按鈕文本欄位應該相應地更新值。
我有多個選項可以在 中設定值InputView,因此,如果我進行了編輯InputView并且單擊了任何按鈕,則該按鈕應更新該值。
這是我的代碼
@main
struct AmountApp: App {
var body: some Scene {
WindowGroup {
InputView()
}
}
}
struct InputView: View {
@State var value: Double = 0.00
var body: some View {
VStack {
Text("Amount")
TextInput(value: $value).padding(.horizontal)
HStack(alignment: .center, spacing: 16) {
Button { value = 20 } label: { Text("20") }
Button { value = 30 } label: { Text("30") }
Button { value = 40 } label: { Text("40") }
}
Button { print(value) } label: {
Text("Print")
.padding(8)
.foregroundColor(.red)
}
}
}
}
struct TextInput: UIViewRepresentable {
@Binding var value: Double
func makeCoordinator() -> Coordinator { Coordinator(self) }
func updateUIView(_ uiView: UITextField, context: Context) { }
func makeUIView(context: Context) -> UITextField {
let textfield = UITextField()
textfield.placeholder = "Enter amount"
textfield.text = "\(value)"
textfield.keyboardType = .decimalPad
textfield.setContentHuggingPriority(.defaultHigh, for: .vertical)
textfield.setContentHuggingPriority(.defaultLow, for: .horizontal)
textfield.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
return textfield
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: TextInput
init(_ textField: TextInput) { self.parent = textField }
}
}
幫助將不勝感激,?美好的一天。!
uj5u.com熱心網友回復:
如果您不實作UITextFieldDelegate接收用戶輸入的方法(SwiftUI Custom TextField with UIViewRepresentable Issue with ObservableObject and push View) ,系結值將不會更新
當您從 SwiftUI 端更改值時,您的 UIViewRepresentable 需要處理 updateUIView 中的更改(將新值傳遞給 UITextField)
還記得設定textfield.delegate = context.coordinator以便您接收事件。
struct TextInput: UIViewRepresentable {
@Binding var value: Double
func makeCoordinator() -> Coordinator { Coordinator(self) }
// for handling swiftui-side modification to the binding (your buttons)
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = value
}
func makeUIView(context: Context) -> UITextField {
let textfield = UITextField()
textfield.placeholder = "Enter amount"
textfield.text = "\(value)"
textfield.keyboardType = .decimalPad
textfield.setContentHuggingPriority(.defaultHigh, for: .vertical)
textfield.setContentHuggingPriority(.defaultLow, for: .horizontal)
textfield.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
textfield.delegate = context.coordinator // set the delegate
return textfield
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: TextInput
init(_ textField: TextInput) { self.parent = textField }
func textFieldDidEndEditing(_ textField: UITextField) {
if let text = textField.text {
parent.value = Double(text) ?? 0
} else {
parent.value = 0
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/448197.html
