wpa
wpa

Reputation: 220

Xcode Autolayout How to centre uitextfield with fixed width that can adjust for smaller screens

I can't seem to form how the constraints will work, so in Descriptive terms:

I can more or less define constraints for most of them except for the ability to constrain its width automatically if the screen shrinks in width for smaller screen sizes.

Some pointers would be good

Thanks!

Upvotes: 1

Views: 1767

Answers (2)

Dima
Dima

Reputation: 23624

This should do it:

let textField = UITextField()
view.addSubview(textField)
textField.translatesAutoresizingMaskIntoConstraints = false

// center horizontally
textField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
// 100 from top layout guide
textField.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: 100).isActive = true

// make sure textfield width never exceeds the superview width
textField.leftAnchor.constraint(greaterThanOrEqualTo: view.leftAnchor).isActive = true
textField.rightAnchor.constraint(lessThanOrEqualTo: view.rightAnchor).isActive = true

// give the textfield its default width, notice the lowered priority which allows this constraint to be broken when needed to satisfy the above constraints
let widthConstraint = textField.widthAnchor.constraint(equalToConstant: 370)
widthConstraint.priority = UILayoutPriorityDefaultHigh
widthConstraint.isActive = true

Upvotes: 2

Rikh
Rikh

Reputation: 4222

You can add a leading and trailing constraint to your textField with a lower priority. And simply add a width constraint that can be <= 370.

Upvotes: 3

Related Questions