在 swift 中以编程方式添加 "Vertical Spacing"

Add "Vertical Spacing" programmatically in swift

我有一个以编程方式添加的 UIImageView 和一个已添加到情节提要中的按钮。现在我需要在它们之间添加 "Vertical Spacing" ,但我不知道该怎么做。如果我在故事板中添加 UIImageView 会很容易:

我该如何解决这个问题?

你应该看看visual format language, and then take a look at the docs on how to programmatically create constraints here。基本上看起来像这样

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

假设您的 UIImageView 被添加到顶部,就像您在上面的图片中添加的那样,那么您可以通过以下方式以编程方式添加约束:

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])
}

在上面的代码中我只设置了垂直的space约束,你需要设置必要的约束以避免关于它的警告。

有几种以编程方式添加约束的方法,您可以在这个非常好的答案中阅读更多内容 SWIFT | Adding constraints programmatically

希望对你有所帮助。

要以编程方式在两个视图之间添加垂直间距,您可以使用以下 Swift 3 代码。

view2是顶视图,view1是底视图。

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

注意:您必须添加水平位置才能正常工作。