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变量.这当然是预期的行为.问题在于,这将导致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屋!