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).
My 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:
I've also tried with:
or instead of Autolayout:
No need to mention NSDirectionEdgeInsets didn't work:
I tried it with a view controller, but still futile:
What am I doing wrong?
My 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:
Code Block swift 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:
Code Block swift rootView.layoutMargins.top = 100
or instead of Autolayout:
Code Block swift let subview = UIView(frame: CGRect(origin: .zero, size: .init(width: 100, height: 100)))
No need to mention NSDirectionEdgeInsets didn't work:
Code Block swift rootView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 100, leading: 100, bottom: 100, trailing: 100)
I tried it with a view controller, but still futile:
Code Block swift 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) } }
What am I doing wrong?