Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the layout margins programmatically

I have very easy setup in viewDidLoad, just add a view and pin it to superview's margins by 'anchors' style:

let myView = UIView(frame: .zero)
myView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(myView)
myView.backgroundColor = UIColor.red
myView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor).isActive = true
myView.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor).isActive = true
myView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor).isActive = true
myView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor).isActive = true
view.layoutMargins = .zero

The problem is that there is still a margin when running this in simulator. Why layoutMargins zeroing is ignored?

enter image description here

like image 789
Viktor Kucera Avatar asked Oct 29 '22 03:10

Viktor Kucera


2 Answers

You need add this in your UIViewController viewWillLayoutSubviews() method

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    view.layoutMargins = .zero
    view.layoutMarginsDidChange()
}

but if you need .zero of margins you can as I said in my comments use view.leadingAnchor as well

like image 109
Reinier Melian Avatar answered Nov 15 '22 05:11

Reinier Melian


Try this.

if #available(iOS 11, *) {
   viewRespectsSystemMinimumLayoutMargins = false
   view.layoutMargins = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
}

Apple document for reference.

like image 37
Sunil Targe Avatar answered Nov 15 '22 07:11

Sunil Targe