以编程方式在swift中添加“垂直间距”

问题描述:

我有一个UIImageView,我已经通过编程添加了一个已添加到故事板中的按钮。现在我需要在它们之间添加“垂直间距”,但我不知道如何去做。会很容易,如果我会加入故事板UIImageView以编程方式在swift中添加“垂直间距”

enter image description here

我该如何解决这个问题呢?

+0

还必须添加约束编程 https://developer.apple.com/library/ios/documentation/AppKit/Reference/NSLayoutConstraint_Class/#//apple_ref/occ/clm/NSLayoutConstraint/constraintWithItem:attribute:relatedBy: toItem:attribute:multiplier:constant: –

让假设你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中阅读更多内容。

我希望这对你有所帮助。

+0

谢谢你的回答,但现在我得到一个错误:“无法激活约束项目 Steve

+0

工作很好,谢谢! – Steve

+1

为什么不是'属性:.Top'? – Liumx31

你应该看看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个视图之间添加垂直间距,您可以使用以下代码Swift 3代码。

view2是顶视图,而查看1的底部视图。

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

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