ios - 将状态/绑定传递给 UIViewRepresentable
问题描述
将状态变量传递给我的自定义文本字段的正确方法是什么?我希望避免其他方法/可观察的。这不应该工作吗?
我在示例项目中重新创建了以下问题。
import SwiftUI
struct ParentView: View {
@State var text: String = "initial"
var body: some View {
VStack {
ChildView(text: $text)
Text(self.text)
}
}
}
struct ChildView: View {
@Binding var text: String
var body: some View {
MyTextField(text: $text).frame(width: 300, height: 40, alignment: .center)
}
}
struct MyTextField: UIViewRepresentable {
@Binding var text: String
func makeUIView(context: Context) -> UITextField {
let view = UITextField()
view.borderStyle = UITextField.BorderStyle.roundedRect
return view
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = text
}
}
解决方案
以您的方式创建一个@Binding
属性CustomTextField
:
struct CustomTextField: UIViewRepresentable {
@Binding var text: String
}
像这样初始化你的@Binding
属性init()
:
init(text: Binding<String>) {
self._text = text
}
text
将属性传递给UITextField
喜欢:
func makeUIView(context: Context) -> UITextField {
// Customise the TextField as you wish
textField.text = text
return textField
}
更新之text
类的UITextField
:
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = self.text
}
@Binding
使用用户输入的文本更新属性,例如:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let value = textField.text as NSString? {
let proposedValue = value.replacingCharacters(in: range, with: string)
parent.text = proposedValue as String // Here is updating
}
return true
}
你ContentView
应该看起来像:
struct ContentView: View {
@State var text: String = ""
var body: some View {
CustomTextField(text: $text)
}
}
好的,如果您想要完整的代码,CustomTextField
请查看此答案。
推荐阅读
- html - 如何指定接受 itemtype 服务的组织类型的属性?
- javascript - Angular - 布尔值不会改变
- javascript - HTML“body onload”仅在手动刷新浏览器时有效
- r - 有没有办法从通过 selectInput 选择的下拉列表中选择或返回所选变量?
- ios - 使用 Ionic 从 iOS Settings-MyApp 读取应用程序设置值
- python - 与另一个数据框合并后无法选择特定列
- javascript - 如何查找前一个字符是否相同
- tensorflow - 如何从`tf.data.Dataset`的填充批次中获取序列长度?
- group-by - group by if partition by used or not used的效果
- sql-server - Chocolatey:安装 SQL SERVER DEVELOPER 版抛出错误