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

时间:2015-07-21 15:12:59

标签: ios swift constraints

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

enter image description here

我该如何解决这个问题?

3 个答案:

答案 0 :(得分: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])
}

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

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

我希望这对你有所帮助。

答案 1 :(得分:3)

您应该查看visual format language,然后查看有关如何以编程方式创建约束here的文档。基本上会看起来像这样

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

答案 2 :(得分:3)

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

view2 是底视图的 view1 时的顶视图。

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

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