[英]Autolayout programmatic aspect ratio setting
我正在嘗試添加一個子視圖來查看和定義自動布局約束,包括縱橫比。 但是我在運行時看到的縱橫比不是我在約束中定義的。 我究竟做錯了什么? 正如您在代碼中看到的,背景視圖高度應該是背景視圖寬度的 0.5,但在屏幕截圖中並非如此。 這是我的代碼:
class ViewController: UIViewController {
private var backgroundView:UIView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.orange
backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
backgroundView?.backgroundColor = UIColor.black.withAlphaComponent(1.0)
backgroundView?.layer.borderColor = UIColor.white.cgColor
backgroundView?.layer.borderWidth = 1.5
backgroundView?.layer.cornerRadius = 4
backgroundView?.clipsToBounds = true
backgroundView?.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(backgroundView!)
backgroundView?.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0).isActive = true
backgroundView?.heightAnchor.constraint(equalTo: backgroundView!.widthAnchor, multiplier: 0.5).isActive = true
backgroundView?.centerXAnchor.constraint(equalTo: view!.centerXAnchor, constant: 0).isActive = true
backgroundView?.topAnchor.constraint(equalTo: view!.topAnchor, constant: 4).isActive = true
}
}
這是屏幕截圖:
“背景視圖高度應該是背景視圖寬度的 0.5”
您的屏幕截圖大小為1334 x 750
您的backgroundView
- 包括邊框 - 是1334 x 667
1334 * 0.5 == 667
所以,你得到的正是你所要求的。
嘗試更改高度約束以設置:
backgroundView?.heightAnchor.constraint(equalTo: view!.heightAnchor, multiplier: 0.5).isActive = true
注意:您正在獲得您正在尋找的確切結果。 它的高度是其寬度的一半。 屏幕截圖沒有任何問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.