5

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Viktor Kucera
  • 6,177
  • 4
  • 32
  • 43

4 Answers4

1

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

Reinier Melian
  • 20,519
  • 3
  • 38
  • 55
  • Hmmm, this will be called multiple times. It's working though. Isn't there any other place/way to do this just once? I don't want to change it dynamically during the view life cycle. – Viktor Kucera Aug 24 '17 at 13:23
  • @ViktorKucera check this question https://stackoverflow.com/questions/27421469/setting-layoutmargins-of-uiview-doesnt-work seems this is the best shot we have, but you can add an subview as alternative solution – Reinier Melian Aug 24 '17 at 13:46
  • yes, is ignored indeed for me is an Apple mistake but is what we have so... no much left to do about it @ViktorKucera – Reinier Melian Aug 24 '17 at 14:18
  • It's fixed in iOS11, I've just tried in Xcode beta. Thanks for help. – Viktor Kucera Aug 24 '17 at 14:37
  • I am glad to hear that seems Apple is fixing his bugs, @ViktorKucera – Reinier Melian Aug 24 '17 at 21:07
1

Try this.

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

Apple document for reference.

Sunil Targe
  • 7,251
  • 5
  • 49
  • 80
0

This seems to be fixed/changed for iOS 11. Lower versions are out of luck.

I've elaborated more in this question

Viktor Kucera
  • 6,177
  • 4
  • 32
  • 43
0

Don't forget self.view.insetsLayoutMarginsFromSafeArea = false which will add on to whatever values you set to self.view.directionalLayoutMargins or self.view.layoutMargins

Seivan
  • 668
  • 6
  • 13