chevi99
chevi99

Reputation: 143

How to write auto layouts for iPhone SE and iPhone 5S programmatically?

I am using auto layout programmatically to layout my views the problem is it works well on iPhone 6s plus but on other screens such as iPhone SE, iPhone 5s and even the X don't render well. Below is my code:

//OK button
view.addSubview(btnOk)
    btnOk.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40).isActive = true
    btnOk.topAnchor.constraint(equalTo: lblRateUsDesc.bottomAnchor, constant: 40).isActive = true
    btnOk.widthAnchor.constraint(equalToConstant: 150).isActive = true
    btnOk.heightAnchor.constraint(equalToConstant: 55).isActive = true

//Later


view.addSubview(btnLater)
    btnLater.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40).isActive = true
    btnLater.topAnchor.constraint(equalTo: lblRateUsDesc.bottomAnchor, constant: 40).isActive = true
    btnLater.widthAnchor.constraint(equalToConstant: 150).isActive = true
    btnLater.heightAnchor.constraint(equalToConstant: 55).isActive = true

This is how iPhone SE renders itThis is how iPhone SE renders it

This is how iPhone X renders itThis is how iPhone X renders it iPhone 6s plus renders it and it is my preferred layoutiPhone 6s plus renders it and it is my preferred layout

Upvotes: 0

Views: 162

Answers (1)

Daniil Subbotin
Daniil Subbotin

Reputation: 6718

The issue is here:

btnOk.widthAnchor.constraint(equalToConstant: 150).isActive = true

iPhone X and iPhone SE, 5s has narrow screen. You should not add constraint to the width property. I recommend you to embed these buttons to Stack View.

iPhone 5s has 320 pt screen width. Two buttons with width 150 pt has total 300 pt width. Left 20 pt for gap and margins. It is not enough. This is the cause for overlapping.

Upvotes: 1

Related Questions