在Swift中以编程方式添加"垂直间距"

8
我有一个通过编程添加的UIImageView和一个在Storyboard中添加的按钮。现在我需要在它们之间添加“垂直间隔”,但我不知道该怎么做。如果我在故事板中添加了UIImageView,那么这将很容易解决: enter image description here 如何解决这个问题呢?

请编写程序来添加约束条件:https://developer.apple.com/library/ios/documentation/AppKit/Reference/NSLayoutConstraint_Class/#//apple_ref/occ/clm/NSLayoutConstraint/constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant: - iamandrewluca
3个回答

14

假设您的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 | 添加约束程序 中了解更多信息。
我希望这可以帮助您。

谢谢您的回答,但是现在我遇到了一个错误:“无法激活约束项<UIImageView...”。可能是我做错了什么,明天再测试一下。 - Steve
3
为什么不是 attribute: .Top - Liumx31
@user245954 因为在上面的情况中,UIImageView 相对于 UIButton 位置靠后,如果你想要改变它,那么你需要交换它们的角色。 - Victor Sigler

5
为了在程序中为两个视图添加垂直间距,您可以使用以下的 Swift 3 代码。 view2 是顶部视图,而 view1 是底部视图。
let verticalSpace = NSLayoutConstraint(item: view1, attribute: .top, relatedBy: .equal, toItem: view2, attribute: .bottom, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([verticalSpace])

注意:为了使此功能正常工作,您必须添加水平位置。


4
你应该查看可视化格式语言,然后查看如何在编程中创建约束的文档这里。基本上会像这样。
    NSDictionary *viewsDictionary =
    NSDictionaryOfVariableBindings(self.imageView, self.button);
    NSArray *constraints =
    [NSLayoutConstraint constraintsWithVisualFormat:@"V:[imageView]-10-[button]"
                                            options:0 metrics:nil views:viewsDictionary];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接