22
Oct
2020
Clip content in wrapped UITextField
Reading time: 1 min
When implementing a custom TextField
by wrapping a UITextField
in UIViewRepresentable
(just like we did in our custom SecureField that tracks focus change, you need to be careful as its size normally grows with its content.
This can lead to the field spilling outside the bounds of its parent, like this:
Note that this is not an issue when using stock SwiftUI TextField
.
Add this magic ingredient to prevent the content size from affecting the text field size:
struct MyTextField: UIViewRepresentable {
func makeUIView(context: UIViewRepresentableContext<MyTextField>) -> UITextField {
let tf = UITextField(frame: .zero)
tf.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) // THIS IS THE KEY
}
}
Your wrapped UITextField
will clip its content to its provided size: