-1

I use this code for add two view on to parent :

let view0 = StarClass.createMyClassView()
parent.addSubview(view0)

let view1 = StarClass.createMyClassView()
parent.addSubview(view1)

This code work fine, but view1 not placed bottom of view0

view1 placed on view0

I want add view1 bottom of view0

How i can ?

salari mameri
  • 228
  • 5
  • 13

1 Answers1

1

You can achieve that by using autolayout, see example below.

    let view0 = StarClass.createMyClassView()
    view0.translatesAutoresizingMaskIntoConstraints = false // Enables autolayout

    parent.addSubview(view0)

    let view1 = StarClass.createMyClassView()
    view1.translatesAutoresizingMaskIntoConstraints = false 
    parent.addSubview(view1)

    NSLayoutConstraint.activate([
        view0.leftAnchor.constraint(equalTo: parent.leftAnchor), // Set layout for view0
        view0.rightAnchor.constraint(equalTo: parent.rightAnchor),
        view0.topAnchor.constraint(equalTo: parent.topAnchor),
        view0.heightAnchor.constraint(equalToConstant: 100),

        view1.leftAnchor.constraint(equalTo: parent.leftAnchor), // Set layout for view1
        view1.rightAnchor.constraint(equalTo: parent.rightAnchor),
        view1.topAnchor.constraint(equalTo: view0.bottomAnchor), // below view0
        view1.heightAnchor.constraint(equalToConstant: 100)
        ])
gugge
  • 918
  • 1
  • 11
  • 17
  • Thank you, best solution for me – salari mameri Jun 26 '18 at 11:40
  • i have another question. how can i use foreach ? sample : for 1...20{ let let view = StarClass.createMyClassView() view.translatesAutoresizingMaskIntoConstraints = false parent.addSubview(view) } . Now, how use NSLayoutConstraint ?! – salari mameri Jun 26 '18 at 12:12
  • You could keep track of the previous added view in a variable, and update it in the loop. Then set the layout in the loop with anchors from the previous view. – gugge Jun 26 '18 at 12:34