13

Updated: I found the answer and fix this issue: (FYI: SwiftUI - State change in UITextField causes the frameWidth to grow uncontrolled and ignore bounds/frame)

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

When I input more and more text in it, the text field will grow wider and wider, even if set frame width.

public struct FoolTextField: UIViewRepresentable {
    @Binding var text: String
    private let textField = UITextField(frame: .zero)

    public init(_ placeholder: String, text: Binding<String>) {
        _text = text
        textField.text = text.wrappedValue
        textField.placeholder = placeholder
        textField.borderStyle = .none
        textField.clearButtonMode = .whileEditing
        textField.returnKeyType = .done
    }
    ...
}


FoolTextField("placeholder", text: $text).frame(width: 200)
foolbear
  • 726
  • 1
  • 7
  • 19

0 Answers0