2015-07-21 227 views
5

我有一個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: –

回答

12

讓假設你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

1

你應該看看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]; 
1

要以編程方式在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]) 

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

相關問題