SwiftUI - State change in UITextField causes the frameWidth to grow uncontrolled and ignore bounds/frame

den*_*nho 19 uitextfield uikit swift swiftui uiviewrepresentable

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?

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 ?? ""
}
Run Code Online (Sandbox Code Playgroud)

How can I update the @State and still keep the textField in the frame?

Asp*_*eri 58

您需要降低内容阻力的优先级makeUIView(因此内容不会推送在 SwiftUI 中设置的外部布局),如下所示

func makeUIView(context: UIViewRepresentableContext<MyField>) -> UITextField {
    let field = UITextField(frame: .zero)
    field.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
    ...
Run Code Online (Sandbox Code Playgroud)

  • 我已经为此苦苦挣扎了几个小时。终于找到了与 Stackoverflow 一起使用的正确咒语,这个问题以及您极其简单的答案出现了。太感谢了! (11认同)
  • 只需花 4 个小时尝试解决这个问题即可。如果我能投票 1000 次我会的!谢谢@Asperi (3认同)