0

I'm currently overlaying a UIView when a button is pressed on top of a viewController. I have it positioned well in other screen devices and when i run in on iPhone X + devices. Its not positioned well. For it to position it well, I need to subtract 40 points to its current top safeAreaInsets. The initial 20 points is to cope with the status bar. When I do this it works and it then doesn't work on the other iPhones that don't have a notch. What I'm doing wrong here. Here is my code

func contentFrame(extraTopOffset pOffset: CGFloat = 0) -> CGRect {
        var theFrame = self.view.bounds
        if let navBar = self.navigationBar {
            let topOffset = navBar.frame.origin.y + navBar.frame.size.height
            theFrame.size.height -= topOffset
            theFrame.origin.y += topOffset
        }
        if #available(iOS 11.0, *) {
            let safeInsets = UIApplication.shared.delegate!.window!?.safeAreaInsets
            let topOffset = safeInsets!.top - (20 + pOffset)
            theFrame.origin.y += topOffset
            theFrame.size.height -= topOffset + safeInsets!.bottom
        }
        return theFrame
    }

Where I show the overlay in another viewController where I override the method

override func showOverlay() {
        self.overlayView.frame = self.contentFrame()
        self.view.addSubview(self.overlayView)
    }

enter image description here

enter image description here

mandem112
  • 181
  • 14

2 Answers2

0

I fixed it by using my implementation. I check if current device has a notch and If it does, I subtract 20 from it. Then add 20 points when I call the method

class var hasNotch: Bool {
        if #available(iOS 11.0, *) {
            return (self.shared.delegate!.window!!.safeAreaInsets.top > 20)
        }
        return false 
    }

func contentFrame(extraTopOffset pOffset: CGFloat = 0) -> CGRect {
        var theFrame = self.view.bounds
        if let navBar = self.navigationBar {
            let topOffset = navBar.frame.origin.y + navBar.frame.size.height
            theFrame.size.height -= topOffset
            theFrame.origin.y += topOffset
        }
        if #available(iOS 11.0, *) {
            let safeInsets = UIApplication.shared.delegate!.window!?.safeAreaInsets
            var extraOffset = safeInsets!.top - 20
            if UIApplication.yb_hasNotch {
                extraOffset -= pOffset
            }
            theFrame.origin.y += extraOffset
            theFrame.size.height -= extraOffset + safeInsets!.bottom
        }
        return theFrame
    }
mandem112
  • 181
  • 14
0

You can use an extension like this.

extension UIDevice {
        var hasNotch: Bool {
            if #available(iOS 11.0, *) {
                let bottom = UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0
                return bottom > 0
            } else {
                return false
            }
        }
    }
tBug
  • 789
  • 9
  • 13