【发布时间】:2021-02-25 14:04:21
【问题描述】:
我一直在 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)
}
}
【问题讨论】:
-
你看过苹果的Positining Content with Layout Margins指南吗?
标签: ios swift autolayout nslayoutconstraint uiedgeinsets