Making translatesAutoResizingMaskIntoConstraints false causes ambiguous layout issue on UITextFields rightview

660 views Asked by At

I don't know whether making every objects translatesAutoresizingMaskIntoConstraints flag false is bad habit but here is my question related with this; I have UITextField object and I am setting its rightView as UIImageView but when UIImageView's translatesAutoresizingMaskIntoConstraints property sets to false in debug view hierarchy ambiguous layout warning appears, apple's documentation says under translatesAutoresizingMaskIntoConstraints topic:

If you want to use Auto Layout to dynamically calculate the size and >position of your view, you must set this property to false, and then >provide a non ambiguous, nonconflicting set of constraints for the view.

but there is method of UITextField

open func rightViewRect(forBounds bounds: CGRect) -> CGRect

that

Returns the drawing location of the receiver’s right overlay view.

Additionally when I am trying to give constraints between rightView and UITextField, it says they are not under same hierarchy. So why making that flag as false causes ambiguous layout?

let imageView = UIImageView(image: UIImage(named: "infoIcon"))
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false //this line causes ambiguous layout
imageView.widthAnchor.constraint(equalToConstant: 15).isActive = true
textField.rightViewMode = .unlessEditing
textField.rightView = imageView
1

There are 1 answers

0
Göktuğ Aral On

I was having a similar issue but in my case I forgot the add translatesAutoresizingMaskIntoConstraints as false.

The things your wrote about translatesAutoresizingMaskIntoConstraints is correct. And usually it is not great couple when you used with set a frame or bounds.

Anyway I tried your code and I have some idea what might be effect;

  • First check your UITextField constraints. If your constraint is not fit well then it could be break after adding rightView.
  • Secondly init your imageView with frame like below;
let imageView = UIImageView(frame: .zero)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = UIImage(named: "logo") imageView.contentMode = .scaleAspectFit
imageView.widthAnchor.constraint(equalToConstant: 15).isActive = true
textField.rightViewMode = .always 
textField.rightView = imageView
  • And finally I think it would be better if you do not use imageView.widthAnchor.constraint(equalToConstant: 15).isActive = true Use an image with best optimal resolution for your textfield and rest would be fine.