你最簡單的選擇將是留在你的方法,並應用基於算法的常量。例如:
func setupProfileImageView() {
//need x, y, width, height constraints
var idealTop : CGFloat = view.frame.height * (some value) //so that it equals a value that changes with each screen size in a way that you feel ok with
idealTop = idealTop < 60 ? 60 : idealTop //makes sure that the constraint doesnt fall bellow 60..
profileImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profileImageView.topAnchor.constraint(equalTo: view.topAnchor, constant: idealTop).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 160).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 160).isActive = true
}
其次,我會建議爲意味着元素被垂直對齊,並在視圖層次結構的同一水平線上,通過類似的方式疏遠他們任何佈局,並通過確保每個元素的topAnchor
指的是它上面的元素bottomAnchor
。一個小技巧,你可以做的,就是你的profileImage的topAnchor的值存儲到一個變量,這樣就可以訪問它的價值的其他元素,就像這樣:
var profileImageTopAnchor : NSLayoutConstraint?
func setupProfileImageView() {
//need x, y, width, height constraints
var idealTop : CGFloat = view.frame.height * (some value) //so that it equals a value that changes with each screen size in a way that you feel ok with
idealTop = idealTop < 60 ? 60 : idealTop //makes sure that the constraint doesnt fall bellow 60..
profileImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profileImageTopAnchor = profileImageView.topAnchor.constraint(equalTo: view.topAnchor, constant: idealTop)
profileImageTopAnchor.isActive = true //otherwise it wont get activated
profileImageView.widthAnchor.constraint(equalToConstant: 160).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 160).isActive = true
}
func setupProfileImageView() {
let topAnchor = profileImageTopAnchor != nil ? profileImageTopAnchor!.constant : (/*Some arbitrary value here .. or repeat as above with a fraction value of the view.frame*/)
let topAnchorValue : CGFloat = topAnchor * (some value) //this way, the spacing will change based on the spacing you declare on top of your image..
//And say that you have three other elements stacked vertically..
elementA.constraint(equalTo: profileImageView.topAnchor, constant: topAnchorValue).isActive = true
elementB.constraint(equalTo: elementA.topAnchor, constant: topAnchorValue).isActive = true
elementC.constraint(equalTo: elementB.topAnchor, constant: topAnchorValue).isActive = true
}
你可以去進一步進入檢測實際屏幕大小,並將其與列表相關聯,以查看使用哪個手機型號..然後應用特定約束......但隨着此句越來越長,上述方法更直接的原因也越來越多!
*會按照我編碼爲* ...好吧,如果您實際給了我們一些**代碼**,那將會很好。 – dfd
我很抱歉,我現在編輯它 – Jaqueline
謝謝。我不理解你的意思。你已經定義了(像我這樣的代碼)就夠了。頂部,高度,最後是水平 - 中心X)。什麼是問題? – dfd