[英]How do you use UIEdgeInsets?
我一直在 Playground 上嘗試不同的方法,但沒有實現邊距。 我試圖了解使用UIEdgeInsets
(和NSDirectionalEdgeInsets
)的正確方法。
期望是超級視圖應該具有指定大小的邊距,而子視圖應該在該邊距內,有點像一個不可見的邊框。
以下沒有顯示超級視圖的任何邊距:
import UIKit
import PlaygroundSupport
let rootView = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
rootView.layoutMargins = UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100)
let subview = UIView()
subview.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
subview.widthAnchor.constraint(equalToConstant: 100),
subview.heightAnchor.constraint(equalToConstant: 100)
])
subview.backgroundColor = .red
rootView.addSubview(subview)
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = rootView
我也試過:
rootView.layoutMargins.top = 100
或代替自動布局:
let subview = UIView(frame: CGRect(origin: .zero, size: .init(width: 100, height: 100)))
嘗試NSDirectionEdgeInsets
,但沒有奏效:
rootView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 100, leading: 100, bottom: 100, trailing: 100)
最后,我在視圖控制器中嘗試了它,但仍然徒勞:
class MyVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let rootView = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
rootView.layoutMargins = UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100)
self.view.addSubview(rootView)
let subview = UIView()
subview.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
subview.widthAnchor.constraint(equalToConstant: 100),
subview.heightAnchor.constraint(equalToConstant: 100)
])
subview.backgroundColor = .red
rootView.addSubview(subview)
}
}
布局邊距不能替代指定視圖位置的約束,它們與此類約束一起工作。 您給出的示例不包含此類約束,因此布局邊距不會產生任何影響。 更重要的是,我的猜測是設置明確的高度和寬度約束會導致任何布局邊距被忽略。
此圖像中展示的布局是使用以下代碼生成的,該代碼使用自動布局的可視格式語言來生成所需的約束。 第一個約束將紅色視圖的垂直邊緣固定到灰色視圖的垂直邊緣,而第二個約束對水平邊緣執行相同的操作。 至關重要的是,格式字符串包含連字符,它向自動布局引擎發出信號,即任何指定的布局邊距也應受到尊重,因此最終布局將紅色視圖的邊緣從灰色視圖的邊緣插入。 如果您刪除這些連字符(例如|[redView]|
),自定義布局邊距將被忽略,您只會讓紅色視圖與灰色視圖的邊緣對齊。
override func viewDidLoad() {
super.viewDidLoad()
let grayView = UIView(frame: CGRect(x: 0, y: 100, width: 300, height: 500))
let customInsets = NSDirectionalEdgeInsets(top: 40, leading: 5, bottom: 20, trailing: 15)
grayView.directionalLayoutMargins = customInsets
grayView.backgroundColor = .lightGray
view.addSubview(grayView)
let redView = UIView()
redView.backgroundColor = .red
redView.translatesAutoresizingMaskIntoConstraints = false
grayView.addSubview(redView)
let vrtConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-[redView]-|", options: [], metrics: nil, views: ["redView":redView])
let hrzConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[redView]-|", options: [], metrics: nil, views: ["redView":redView])
NSLayoutConstraint.activate(verticalEdgeConstraints + horizontalEdgeConstraints)
}
當然,您不必使用視覺格式字符串來滿足布局邊距:您還可以通過界面構建器“選擇加入”。 此選項在 Apple 的帶有布局邊距的定位內容指南中進行了探討
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.