簡體   English   中英

以編程方式快速更改縱橫比約束

[英]Swift change aspect ratio constraint programmatically

我們有一個帶有UIButton的 MainStoryBoard 和帶有 4 個約束的UIView foo

  • foo 頂部到 superView 頂部
  • foo 導致 superView 領先
  • 尾隨 foo 到 superView 尾隨
  • foo 縱橫比 16:9

按鈕的預期行為應該是它更改 foo 約束,因此 foo 將擴展到全屏,如果再次按下它應該具有以前的縱橫比,16:9。

我嘗試按照以下步驟使用約束的IBOutlet執行此操作:

  • 展開:
    • 從 foo 中刪除 aspectRatio 約束
    • 向 superView 底部添加 foo 底部約束
  • 崩潰時:
    • 將 foo 底部約束移除到 superView 底部
    • 將 aspectRatio 約束添加到 foo

我也玩過高度,什么都沒有。 提前致謝。

您的初始約束應如下所示。

NSLayoutConstraint.activate([
    foo.leadingAnchor.constraint(equalTo: superView.leadingAnchor),
    foo.trailingAnchor.constraint(equalTo: superView.trailingAnchor),
    foo.topAnchor.constraint(equalTo: superView.topAnchor)
])

let collapsedConstraint = foo.heightAnchor.constraint(equalTo: foo.widthAnchor, multiplier: 9/16)
let expandedConstraint = foo.bottomAnchor.constraint(equalTo: superView.bottomAnchor)
collapsedConstraint.isActive = collapsed
expandedConstraint.isActive = !collapsed

被觸發的方法應該像這樣改變約束。

@objc func tapAction() {
    collapsedConstraint.isActive = collapsed
    expandedConstraint.isActive = !collapsed
    superView.layoutIfNeeded()
}

暫無
暫無

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

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