【发布时间】:2022-06-10 22:11:13
【问题描述】:
我想在 swiftUI 中创建待办事项列表功能,例如当用户输入18 January 时,它会识别它并更改字符串特定部分的背景颜色。
目前,swiftUI TextFiled 不支持属性字符串,所以我们必须使用 UITextFiled。
struct ContentView: View {
@State var text : String = ""
var body: some View {
VStack {
CustomTextView(text: $text2) { text in
print(text)
}
.background(Color.gray.opacity(0.5))
.frame(height: 50)
.padding()
}
}
}
struct CustomTextView : UIViewRepresentable {
@Binding var text : String
var onCommit: (String) -> Void
class Coordinator : NSObject, UITextFieldDelegate {
var parent : CustomTextView
var onCommit : (String) -> Void
init(_ parent : CustomTextView,onCommit : @escaping (String) -> Void ) {
self.parent = parent
self.onCommit = onCommit
}
func textFiledDidChange(_ textFiled : UITextField) {
self.parent.$text.wrappedValue = textFiled.text ?? ""
}
func textFieldDidEndEditing(_ textFiled : UITextField) {
self.onCommit(textFiled.text ?? "")
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self, onCommit: onCommit)
}
func makeUIView(context: Context) -> UITextField {
let textFiled = UITextField()
textFiled.delegate = context.coordinator
textFiled.autocorrectionType = .no
textFiled.autocapitalizationType = .none
return textFiled
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = text
}
}
在这个例子中如何使用属性字符串?
【问题讨论】:
-
SwiftUI TextField 不支持属性字符串,请考虑使用 UITextField 作为可表示的解决方案。
-
@Asperi 我添加了 UITextFiled 并且它工作正常但是如何在 UITextFiled 中使用属性字符串?我应该在 UIViewRepresentable 的
updateUIView函数中使用它吗?我可以更新这个问题还是问一个新问题,我有一点 UIKit 的背景谢谢你的帮助 -
这里是一个例子stackoverflow.com/a/60999136/12299030,用
attributedText代替text -
@Asperi 抱歉,我更新了我的问题,如果您再看一遍,不胜感激。
标签: swiftui