I've been trying different ways on the Playground, but the margins are not being implemented. I'm trying to understand the proper way of using UIEdgeInsets
(and NSDirectionalEdgeInsets
).
The expectation is that the super view should have margins of specified size and the subview should be within that margin, sort of like an invisible border.
Following didn't show any margins for the superview:
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
I've also tried with:
rootView.layoutMargins.top = 100
or instead of Autolayout:
let subview = UIView(frame: CGRect(origin: .zero, size: .init(width: 100, height: 100)))
tried NSDirectionEdgeInsets
, but didn't work:
rootView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 100, leading: 100, bottom: 100, trailing: 100)
Finally, I tried it within a view controller, but still futile:
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)
}
}