Search code examples
iosswiftuikit

What is the right way to arrange bottom button so that it doesn't leave a white area at the bottom of screen?


For UIToolbar, if we use constraint

toolbar bottom = safe area bottom

enter image description here

It will work pretty well.


However, if I apply the same technique for UIButton

button bottom = safe area bottom

enter image description here

They will be an undesired white area at the bottom


Most suggestions are using

button bottom = super view bottom

enter image description here

However, if using this technique, I need to adjust the height of button with the following logic.

if iPhone SE {
    button height = 44
} else {
    button height = 44 + ???
}

May I know, what is the right way to arrange bottom button so that it doesn't leave a white area at the bottom of screen?


Solution

  • You should constraint the button's bottom to the superview's bottom, not the safe area's bottom.

    The logic to adjust the button's height is simple - you add a top constraint that is relative to the bottom of the safe area.

    override func viewDidLoad() {
        super.viewDidLoad()
        let buttonHeight = 36
        button.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -buttonHeight).isActive = true
    }
    
    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        button.configuration!.contentInsets.bottom = view.safeAreaInsets.bottom
        
    }
    

    Note that I also set the content inset of the button, so that the button's title is not vertically centered. We want the title to move up a little so that it is in the safe area.