Forest Kunecke
Forest Kunecke

Reputation: 2160

Keep UIButton in front in TabBar

I'm subclassing UITabBarController and I'm trying to add a button to the center of the tab bar. It shows up nicely at first:

enter image description here

Then when I select an item in my TableViewController, it stays visible:

enter image description here

Additionally, when I navigate back to the TableViewController, the button now appears behind the tab bar:

enter image description here

This is the code I'm using to add the button:

class PhotoTabBarController: UITabBarController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    addPhotoButton()
}

// ...

func addPhotoButton() {
    let button = UploadButton(frame: CGRect(x: 0, y: 0, width: 60, height: 60))


    // Start of code to center button in the tab bar

    let heightDifference = button.frame.size.height - self.tabBar.frame.size.height;
    // if the height of the center button is less than the height of the tab bar...
    if (heightDifference < 0) {
        // center the button inside the tab bar
        button.center = self.tabBar.center;
    } else {

        var center = self.tabBar.center;
        center.y = center.y - heightDifference/2.0 - 5
        button.center = center;
    }

    self.view.addSubview(button)
    self.view.bringSubview(toFront: button)
}
}

The look of the button is created in the draw(_ rect: CGRect) function.

Is there something I can do to make it so the button hides with the tab bar when a cell is selected, and is brought to the front when navigating back to the TableViewController?

Upvotes: 2

Views: 634

Answers (1)

user7212452
user7212452

Reputation:

Add this button to tabBarController.view

self.tabBarController.view.addSubview(button)

Upvotes: 1

Related Questions