8

I have an UIImageView that I've added programmatically and a button which has been added in a Storyboard. And now I need to add "Vertical Spacing" between them, but I don't know how to do it. Would be easy if I would have added UIImageView in storyboard:

enter image description here

How can i solve the problem ?

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
Steve
  • 722
  • 4
  • 10
  • 24
  • you must also add constraints programmatically https://developer.apple.com/library/ios/documentation/AppKit/Reference/NSLayoutConstraint_Class/#//apple_ref/occ/clm/NSLayoutConstraint/constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant: – iamandrewluca Jul 21 '15 at 15:22

3 Answers3

14

Let suppose your UIImageView is added in the top as you put in your image above, then you can add constraints programmatically like in the following way:

override func viewDidLoad() {
    super.viewDidLoad()

    // assuming here you have added the self.imageView to the main view and it was declared before. 
    self.imageView.setTranslatesAutoresizingMaskIntoConstraints(false)

   // create the constraints with the constant value you want.
   var verticalSpace = NSLayoutConstraint(item: self.imageView, attribute: .Bottom, relatedBy: .Equal, toItem: self.button, attribute: .Bottom, multiplier: 1, constant: 50)

  // activate the constraints
  NSLayoutConstraint.activateConstraints([verticalSpace])
}

In the above code I only put the vertical space constraints, you need to set the necessary constraints to avoid warnings about it.

There are several ways of adding constraint programmatically you can read more in this very nice answer SWIFT | Adding constraints programmatically.

I hope this help you.

Community
  • 1
  • 1
Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
5

To add a vertical spacing between 2 views programmatically, you can use the following Swift 3 code.

view2 is the top view while view1 of the bottom view.

let verticalSpace = NSLayoutConstraint(item: view1, attribute: .top, relatedBy: .equal, toItem: view2, attribute: .bottom, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([verticalSpace])

Note: You must add the horizontal position for this to work.

Eduardo Irias
  • 1,043
  • 11
  • 12
4

You should take a look at the visual format language, and then take a look at the docs on how to programmatically create constraints here. Basically would look something like this

    NSDictionary *viewsDictionary =
    NSDictionaryOfVariableBindings(self.imageView, self.button);
    NSArray *constraints =
    [NSLayoutConstraint constraintsWithVisualFormat:@"V:[imageView]-10-[button]"
                                            options:0 metrics:nil views:viewsDictionary];
David Cao
  • 525
  • 3
  • 11