Search code examples
iosswiftautolayout

How to have different constants for bottom anchor for iPhone 8 screen vs iPhone X and above?


I have done a bit of research but i'm stuck at finding the answer on this one: I want to maintain a constant of -6 from the bottom of the screen to the bottom of a menu for pre iPhone X screen type. When running on X or above the constant is 0 as it is not needed. I have tried verifying the iOS version but obviously it always defaults to the safeAreaLayoutGuide on the model 8. what should I do? i am only thinking of more "manual" solutions like screen height but I know this is not the way to go. pls help. code below.

view.addSubview(programMainMenu)
        if #available(iOS 11.0, *) { // gets called on 8.
            let safeGuide = self.view.safeAreaLayoutGuide
            let safeMenuConstraints = [
                programMainMenu.bottomAnchor.constraint(equalTo: safeGuide.bottomAnchor, constant: 0),
                programMainMenu.leadingAnchor.constraint(equalTo: safeGuide.leadingAnchor, constant: 8),
                programMainMenu.trailingAnchor.constraint(equalTo: safeGuide.trailingAnchor, constant: -8),
                programMainMenu.heightAnchor.constraint(equalToConstant: 90)
            ]
            NSLayoutConstraint.activate(safeMenuConstraints)
        } else {
            let mainMenuConstraints = [
                programMainMenu.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -6), // i need to have this on 8 but not above
                programMainMenu.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8),
                programMainMenu.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8),
                programMainMenu.heightAnchor.constraint(equalToConstant: 90)
            ]
            NSLayoutConstraint.activate(mainMenuConstraints)
        }*

Solution

  • You need

     var cons = 0 // set values for it inside each switch case 
    
    if UIDevice().userInterfaceIdiom == .phone {
        switch UIScreen.main.nativeBounds.height {
            case 1136:
                print("iPhone 5 or 5S or 5C")
               cons = ///
    
            case 1334:
                print("iPhone 6/6S/7/8")
    
            case 1920, 2208:
                print("iPhone 6+/6S+/7+/8+")
    
            case 2436:
                print("iPhone X/XS/11 Pro")
    
            case 2688:
                print("iPhone XS Max/11 Pro Max")
    
            case 1792:
                print("iPhone XR/ 11 ")
    
            default:
                print("Unknown")
            }
        }
    

    Then use the var here

    programMainMenu.bottomAnchor.constraint(equalTo: safeGuide.bottomAnchor,
    constant:cons),