[英]How to change Width in a UITextField with UIViewRepresentable in SwiftUI?
I am new in IOS and working on the SwiftUI. I wrapped UITextField in the SwiftUI using UIViewRepresentable.我是 IOS 的新手,正在研究 SwiftUI。我使用 UIViewRepresentable 将 UITextField 包裹在 SwiftUI 中。 But the issue is:但问题是:
I am unable to fix the wrapped UITextField width and height.我无法修复包裹的 UITextField 宽度和高度。 The text writes only in one line and increases the width of the UITextfield when writing more text.文本只写一行,写多了就增加UITextfield的宽度。
Here is my code:这是我的代码:
struct SecondWrappedTextField: UIViewRepresentable {
@Binding var text: String // Declare a binding value
func makeUIView(context: Context) -> UITextField {
let textField = UITextField()
textField.delegate = context.coordinator
textField.textAlignment = .left
textField.contentVerticalAlignment = .top
return textField
}
func updateUIView(_ uiView: UITextField, context: Context) {
uiView.text = text // 1. Read the binded
print("Selcted Text")
let getSelectedText=UserDefaults.standard.string(forKey: text) ?? ""
let mainString = text
let stringToColor = getSelectedText
let range = (mainString as NSString).range(of: stringToColor)
let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)
uiView.attributedText = mutableAttributedString
}
func makeCoordinator() -> Coordinator {
return Coordinator(text: $text)
}
class Coordinator: NSObject, UITextFieldDelegate,ObservableObject {
@Binding var text: String
init(text: Binding<String>) {
self._text = text
}
func textFieldDidChangeSelection(_ textField: UITextField) {
DispatchQueue.main.async {
self.text = textField.text ?? "" // 2. Write to the binded
let abc = textField // 2. Write to the binded
print("TEXT")
print(self.text)
}
}
}
}
SecondWrappedTextField(text: $textNote).multilineTextAlignment(.leading).background(Color.white).frame(width:200,height:200)
Sorry for the bad English.[Image]抱歉英语不好。[图片]
So if you want to have multiline editable text field, you should use UITextView as UIViewRepresentable.所以如果你想要多行可编辑的文本字段,你应该使用 UITextView 作为 UIViewRepresentable。
This is an example tutorial by Prafulla Singh, it works amazingly in my project.这是 Prafulla Singh 的示例教程,它在我的项目中效果惊人。 https://betterprogramming.pub/swiftui-multiline-content-fit-textfield-3abbdcedaabc https://betterprogramming.pub/swiftui-multiline-content-fit-textfield-3abbdcedaabc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.