Elisey Ozerov
Elisey Ozerov

Reputation: 230

How to change UITextField size inside UIViewRepresentable in SwiftUI

I want to make a simple custom UITextField and I can't figure out how to set its height.

The problem is the UITextField expands to fill parent, and I realise I can set .frame() modifier on the UINumberTextView, but that isn't a good solution because you don't need to do that on a SwiftUI TextField. I'm beyond frustrated on this as I haven't found an answer anywhere and it's such a simple problem.

Here's my code - setting textfield.frame has no effect whatsoever.

struct UINumberTextView: UIViewRepresentable {

    @Binding var text: String

    func makeUIView(context: Context) -> UITextField {
        let textfield = UITextField()
        textfield.keyboardType = .numberPad
        textfield.frame = CGRect(origin: .zero, size: CGSize(width: .max, height: 44))
    
        return textfield
    }

    func updateUIView(_ uiView: UITextField, context: Context) {
        uiView.text = text
    }
}

Here's how the preview looks like

Here's how this code looks in the preview.

Upvotes: 5

Views: 1540

Answers (1)

Rico Crescenzio
Rico Crescenzio

Reputation: 4226

You have to change the compression resistance priority

textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)

Upvotes: 9

Related Questions