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

Ste*_*eve 7 constraints ios swift

我有一个UIImageView以编程方式添加的内容和一个已添加到Storyboard中的按钮.现在我需要在它们之间添加"垂直间距",但我不知道该怎么做.如果我UIImageView在故事板中添加会很容易:

在此输入图像描述

我该如何解决这个问题?

Vic*_*ler 13

假设您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])
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中我只提出了垂直空间约束,你需要设置必要的约束来避免它的警告.

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

我希望这对你有帮助.

  • 为什么不是`属性:.Top`? (3认同)

Edu*_*ias 5

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

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

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

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