SwiftUI - UITextField 中的状态更改导致 frameWidth 不受控制地增长并忽略边界/框架 [英] SwiftUI - State change in UITextField causes the frameWidth to grow uncontrolled and ignore bounds/frame
问题描述
我正在使用 SwiftUI 并连接到 UITextField(我需要分配 firstResponder).我使用这里的代码:SwiftUI:如何制作TextField 成为第一响应者?
I am using SwiftUI and bridge to UITextField (I need to assign firstResponder). I use the code from here: SwiftUI: How to make TextField become first responder?
以下代码更新我的@Binding var.这当然是预期的行为.问题是这会导致 textField 忽略框架/边界.它只是扩展并将其他元素推出视图.视图的其他部分也依赖于@State.
The following code updates my @Binding var. This of course is intended behavior. The problem is that this causes the textField to ignore the frame/ bounds. It just expands and pushes other elements out of the view. Other parts of the view are also reliant on the @State.
func textFieldDidChangeSelection(_ textField: UITextField) {
text = textField.text ?? ""
}
如何更新 @State 并仍然将 textField 保留在框架中?
How can I update the @State and still keep the textField in the frame?
推荐答案
你需要在 makeUIView
中降低内容阻力的优先级(这样内容不会推送在 SwiftUI 中设置的外部布局),如下所示>
You need to decrease priority of content resistance in makeUIView
(so content would not push external layout set in SwiftUI) like below
func makeUIView(context: UIViewRepresentableContext<MyField>) -> UITextField {
let field = UITextField(frame: .zero)
field.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
...
这篇关于SwiftUI - UITextField 中的状态更改导致 frameWidth 不受控制地增长并忽略边界/框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!