Andrew Qin
Andrew Qin

Reputation: 67

Xcode Split the Screen into 4 Giant Buttons

I have figured out how to use auto layout to make all buttons visible, but I am stuck in one particular goal:

I am trying to divide the screen into 4 giant buttons, each button occupies 1/2 of the screen height and 1/2 of the screen width, with no spacing between each other. I tried setting constraints, but the buttons would not display properly.

Please see the two images I posted here, I want to make it so that the iPhone SE view looks the same as the iPhone 7 view. Last time I posted similar question my reputation got decreased, although I did not know why, I am someone who has just started on my own and am trying to figure things out so please advice. Thank you!

iPhone7View

iPhoneSEView

Upvotes: 1

Views: 430

Answers (3)

Krunal
Krunal

Reputation: 79726

Follow these steps: (Very simple easy to implement)

  1. Remove all constrains from all your views (Orange, Red, Blue and Green)
  2. Select All Four Views and assign Top, Bottom, Leading & Trailing constraint with constant value = 0 (with respect to position you have shown in your snapshot)
  3. Select Orange and Red views and assign Equal Width Constraint
  4. Select Blue and Green views and assign Equal Width Constraint
  5. Select Orange and Blue views and assign Equal Height Constraint
  6. Select Red and Green views and assign Equal Height Constraint

Look at this snapshot (Reference constraints, for all button are mentioned in left pane)

enter image description here

Final View: enter image description here

Upvotes: 1

Hamdullah shah
Hamdullah shah

Reputation: 804

Following is the screenshot of constraints for your desired layout. enter image description here

I'm gonna attach the storyboard also. File Download Link

Without Top and Bottom Views

enter image description here

File Download Link

Upvotes: 2

Ryan Poolos
Ryan Poolos

Reputation: 18561

This can be done with constraints but it can also be easily done with stackViews.

let button1 = UIButton()
button1.backgroundColor = .red
let button2 = UIButton()
button2.backgroundColor = .blue
let button3 = UIButton()
button3.backgroundColor = .green
let button4 = UIButton()
button4.backgroundColor = .orange

let topStack = UIStackView(arrangedSubviews: [button1, button2])
topStack.axis = .horizontal
topStack.distribution = .fillEqually

let bottomStack = UIStackView(arrangedSubviews: [button3, button4])
bottomStack.axis = .horizontal
bottomStack.distribution = .fillEqually

let stackView = UIStackView(arrangedSubviews: [topStack, bottomStack])
stackView.axis = .vertical
stackView.distribution = .fillEqually

stackView.frame = view.bounds
stackView.autoresizingMask = [.flexibleHeight, .flexibleWidth]

view.addSubview(stackView)

Upvotes: 1

Related Questions