swiftautolayoutconstraintsiphone-xpagecontrol

Auto Layout not properly handling iPhone X notch


I have implemented a pageViewIndicator to the top of my application using swift. I have constantly tested it on my personal iPhone, which has worked, but when using the iPhone X simulator, I have noticed that it disappears behind the notch, simply because I did not reference to place it within the safe area or the safe area is not properly configured yet. Here is the comparison:

pageController on iPhone 8 pageController on iPhone X

It seems like an easy question, yet I currently have not found any proper support on how to handle this: the main suggestion is to adjust the safeAreaInsets, yet I do not understand how to apply this to the AutoLayout functionality. I have tried adding a topAnchor constraint to the pageController, yet would it even be possible editing this using basic arithmetic?

pageControl.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true

Solution

  • I have found my problem, which was actually something I have simply overseen: I forgot to add

    pageControl.translatesAutoresizingMaskIntoConstraints = false

    to the pageControl before adding it as a subview. With this, I was able to assign following constraints to properly position my pageController where I wanted it to be:

    let safeViewMargins = self.view.safeAreaLayoutGuide
    pageControl.topAnchor.constraint(equalTo: safeViewMargins.topAnchor).isActive = true
    pageControl.leadingAnchor.constraint(equalTo: safeViewMargins.leadingAnchor).isActive = true
    pageControl.trailingAnchor.constraint(equalTo: safeViewMargins.trailingAnchor).isActive = true
    

    This then perfectly ran on all devices.