skip to Main Content

I’m working on an custom tab bar button stuff and want to know how can I move up the button using the view’s height or something programatically.

enter image description here

I have this plus button and I want to move up 10pt from the bottom.

let newButton = UIButton(frame: CGRect(x: 0, y: 0, width: 65, height: 65))
newButton.imageView?.contentMode = .scaleAspectFit
newButton.contentHorizontalAlignment = .fill
newButton.contentVerticalAlignment = .fill
      
var newButtonFrame = newEventButton.frame
newButtonFrame.origin.y = view.bounds.height - 65 - 10

So the code above works when an iPhone doesn’t have a home button notch. Like get the height of the view and subtract button height and 10.

But, obviously, when there is a notch, it becomes something like the image below.
enter image description here

I want to move up the button from the bottom of the tabbar, so how can I get the height of the screen till the bottom of the tabbar, which works on both with/without home notch?

2

Answers


  1. For button origin use safe are insets, ıf device has notch safeAreaBottom will be like 44 , if not it will be 0:

    let safeAreaBottom = UIApplication.shared.windows.first?.safeAreaInsets.bottom
    

    Then use it :

    newButtonFrame.origin.y = view.bounds.height - safeAreaBottom - 65 - 10
    
    Login or Signup to reply.
  2. While @wonder is completly correct in his answer, there are still some flaws.

    First you shouldn’t use frame to determine views layout like this.

    Second there are no need to reach into the UIApplication singleton of windows for this. As it’s located in the parents view. Either in safeAreaInsets or safeAreaLayoutGuide.

    The layout guide is for anchor points, which is way more sustainable than frames.

    Here you have example code of how it can look:

    let newButton = UIButton()
    newButton.imageView?.contentMode = .scaleAspectFit
    newButton.contentHorizontalAlignment = .fill
    newButton.contentVerticalAlignment = .fill
    NSLayoutConstraint.activate([
        newButton.heightAnchor.constraint(equalTo: 65),
        newButton.widthAnchor.constraint(equalTo: 65),
        newButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        newButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -10)
    ])
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search