簡體   English   中英

如何在 StoryBoard 中更新 NSLayoutConstraint?

[英]How to Update NSLayoutConstraint in StoryBoard?

我在 superView 中創建了 2 個 Button,現在我想更改@IBOutlet weak var bottomLayOut: NSLayoutConstraint! 取決於用戶角色。

示例是:如果用戶是代理角色但不是教師角色,我想將NSLayoutConstraint的第二項從 Teacher Entry .bottom 更新為 AgentEntry 按鈕的 bottom 。

在此處輸入圖像描述 那可能嗎?

更新 :

通過將translatesAutoresizingMaskIntoConstraints為 true 來解決這個問題:例如: teacherBtn.translatesAutoresizingMaskIntoConstraints = true比,我們可以同時使用約束和代碼來更改 teacherBtn 的框架

我可以想到兩種方法來做到這一點:

  1. 以編程方式設置約束。 創建一個包含按鈕當前約束的屬性,然后您可以執行以下操作(免責聲明:用 Chrome 編寫,可能包含拼寫錯誤,酌情編輯):

` 如果讓約束 = self.buttonConstraints { NSLayoutConstraint.deactivate(constraints) }

let views: [String : UIView] = ["Agent" : self.agentButton, "Teacher" : self.teacherButton]

let newConstraints: [NSLayoutConstraint] = {
    switch role {
    case .teacherAndAgent:
        self.teacherButton.isHidden = false
        self.agentButton.isHidden = false
        return NSLayoutConstraint.constraints(withVisualFormat: "V:[agent]-[teacher]-|", metrics: nil, views: views)
    case .teacherOnly:
        // you get the idea
    case .agentOnly:
        // ditto
    }
}()

NSLayoutConstraint.activate(newConstraints)
self.buttonConstraints = newConstraints`
  1. 不過,可能更簡單的是使用 UIStackView 來保存您的按鈕。 至少在當前的 macOS 上,NSStackView 會根據隱藏的視圖自動調整布局; 如果 iOS 上的 UIStackView 的行為方式相同,它可能會為您完成很多工作,而無需手動處理布局約束。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM