Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Vertical Spacing between two views programmatically in swift

I have these views, both are the same, i want to add them programmatically so i want to add constraints programmatically, i've managed to do same using storyboard but i want to use code for this.

this is what i want to create

i want to add margins to these views so that first one is at the top, next one is below the first one and so,

i've wrote code like this:

self.view.addConstraint(
    NSLayoutConstraint(
        item: secondView,
        attribute: .Top,
        relatedBy: .Equal,
        toItem: firstView,
        attribute: .Top,
        multiplier: 1.0,
        constant: 0
    ))

first view has the constraint in which toItem is current view controller and it works, but the second view does not work this way, it just draws it on top of the first view, i want it to be below it, only way i can do this is in constant: 0 enter the height of the view, which i don't like

any suggestions?

like image 380
nikagar4 Avatar asked Feb 07 '23 06:02

nikagar4


1 Answers

The code you supplied is 99% right but

self.view.addConstraint(
    NSLayoutConstraint(
        item: secondView,
        attribute: .Top,
        relatedBy: .Equal,
        toItem: firstView,
        attribute: .Top,
        multiplier: 1.0,
        constant: 0
    ))

Your attaching the top of secondView to the top of firstView so they would be on top instead you want the top of secondView to the bottom of firstView.

self.view.addConstraint(
    NSLayoutConstraint(
        item: secondView,
        attribute: .Top,
        relatedBy: .Equal,
        toItem: firstView,
        attribute: .Bottom,  <----------
        multiplier: 1.0,
        constant: 0
    ))

The constant is the distance.

like image 153
Sean Lintern Avatar answered Feb 09 '23 19:02

Sean Lintern