Sobes.tech
Junior — Middle

How to divide the screen into three equal parts using three Views?

sobes.tech AI

Answer from AI

To divide the screen into three equal parts using three UIViews in iOS, you can use Auto Layout and set each of the three views to have the same height (or width if dividing horizontally) and arrange them one below the other (or side by side).

Example with vertical arrangement:

let view1 = UIView()
let view2 = UIView()
let view3 = UIView()

// Add to superview
superview.addSubview(view1)
superview.addSubview(view2)
superview.addSubview(view3)

// Disable autoresizing mask
view1.translatesAutoresizingMaskIntoConstraints = false
view2.translatesAutoresizingMaskIntoConstraints = false
view3.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([
    // Pin view1 to the top of the superview
    view1.topAnchor.constraint(equalTo: superview.topAnchor),
    view1.leadingAnchor.constraint(equalTo: superview.leadingAnchor),
    view1.trailingAnchor.constraint(equalTo: superview.trailingAnchor),

    // view2 below view1
    view2.topAnchor.constraint(equalTo: view1.bottomAnchor),
    view2.leadingAnchor.constraint(equalTo: superview.leadingAnchor),
    view2.trailingAnchor.constraint(equalTo: superview.trailingAnchor),

    // view3 below view2
    view3.topAnchor.constraint(equalTo: view2.bottomAnchor),
    view3.leadingAnchor.constraint(equalTo: superview.leadingAnchor),
    view3.trailingAnchor.constraint(equalTo: superview.trailingAnchor),
    view3.bottomAnchor.constraint(equalTo: superview.bottomAnchor),

    // All three views have the same height
    view1.heightAnchor.constraint(equalTo: view2.heightAnchor),
    view2.heightAnchor.constraint(equalTo: view3.heightAnchor)
])

This way, the screen will be divided into three equal parts by height.

How to divide the screen into three equal parts using… - sobes.tech