2013-07-10 53 views
2

在視圖中我插入一個新的UIButton,因爲我一直在使用AutoLayout,我需要獲取下面的視圖的約束,我將要插入按鈕。如何以編程方式獲取NSLayoutConstraint,以便我可以刪除舊約束,然後創建新約束。感謝名單。如何在UIButton之間以編程方式獲取NSLayoutConstraint?

編輯:enter image description here

與裁判圖,我需要B1和B2之間插入B3,所以,我需要刪除B1和B2之間的已經設定的固定空間約束,並且我需要B3底部連接到B2的頂部和B3的頂部到B1的底部。

+0

您是否確定需要刪除約束?你能展示一個關於約束條件的圖表/代碼嗎? – Fogmeister

+0

請檢查編輯 – Newbee

+0

酷,好吧,你需要刪除。好吧,給我一秒...實際上,現在不能回答。看看從這裏鏈接的github項目雖然http://www.oliverfoggin.com/an-auto-layout-experiment/我做了很多。 – Fogmeister

回答

0

您可以關閉應用於視圖的默認約束,如下所示。當您第一次創建按鈕編程時,應用下面的代碼。

B1.translatesAutoresizingMaskIntoConstraints = NO; 
B2.translatesAutoresizingMaskIntoConstraints = NO; 
B3.translatesAutoresizingMaskIntoConstraints = NO; 

將所有按鈕的使用AddSubView您查看後重新設定你的約束與參數你需要下面的例子。

// Center the middle one vertically 
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:B2 attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0]]; 

希望這有助於你我找到最好的答案在堆棧飛越從 Evenly space multiple views within a container view 鋁是最好的。

+0

謝謝你的回答,我會檢查並讓你知道。 – Newbee

+0

嘗試了你的代碼..新的按鈕放置在第二個項目的位置(在你的情況self.view)而不是通過下移第二個按鈕。 – Newbee

+0

避免我的示例只是使用translatesAutoresizingMaskIntoConstraints轉換默認約束並僅應用您的邏輯 –

2

我需要刪除B1和B2

之間已經設定的固定空間限制查找約束編程

您可以在視圖中限制搜索B1,或保持對它的引用當您創建它時,請使用NSLayoutConstraint。搜索B1的約束可能效率較低:所有關係約束(查看另一個視圖)都是包含superview的一部分。假設你有一個手柄B1,你可以列出所有B1約束它的父像這樣:

// Searching all relationship constraints involving b1 
for item in self.view.constraints() { 
    if let constraint = item as? NSLayoutConstraint { 
     if let button = constraint.firstItem as? UIButton { 
      if button == b1 { 
       println("firstItem found: \(constraint)") 
      } 
     } 
     if let button = constraint.secondItem as? UIButton { 
      if button == b1 { 
       println("secondItem found: \(constraint)") 
      } 
     } 
    } 
} 

記住約束

到目前爲止,清潔方法是保持到NSLayoutConstraint你想有一個參考以後修改或刪除。要在Storyboard中執行此操作,請創建您需要的約束。

enter image description here

然後直接控制拖動參考到您的源文件後操縱它們。

enter image description here