Search code examples
iosswiftautolayouttraitsiphone12

Manage bottom button in iphone8 & iphone12 swift


In iPhone8 like rectangle edge devices, I need a bottom button stuck on the bottom edge with sharp corners. And in iPhone12 like curved edge devices, I need a bottom button with some distance on right-left-bottom with a corner radius.

How can I manage it on the storyboard? Please check the below image for better understanding.

enter image description here

enter image description here


Solution

  • As far as I know, the storyboard has no straightforward way to achieve this. If I were you, I'll

    1. Check whether the device has curved edges(i.e the device is iPhone X or higher model) or not and then
    2. Set button constraints programmatically based on the above check.

    There's no official API provided for checking whether the device has curved edges or not but here's my solution so if anyone knows a better hack, please let me know.

    extension UIDevice {
        var iPhoneXOrAboveModel: Bool {
            return UIScreen.main.nativeBounds.height >= 2436
        }
    }
    

    Now, you can use this extension inside your view controller and constraint your button.

    if UIDevice.current.iPhoneXOrAboveModel {
                // Has curved edges
                NSLayoutConstraint.activate([
                    button.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
                    button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant:  -20)
                ])
                button.layer.cornerRadius = 12
            } else {
                // Has square edges
                NSLayoutConstraint.activate([
                    button.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                    button.trailingAnchor.constraint(equalTo: view.trailingAnchor)
                ])
            }