Search code examples
iosswiftuitabbarcontrollerfloating-action-button

Adding float action button to a view controller inside tab bar controller


I am using a custom floating action button (Floaty) that I want to add programmatically to my UITableViewController which is inside a UITabBarController. The issue is that the bottom tab bar is overlayed on top of the floating action button.

Inside my table view controller:

let floaty = Floaty()
...
self.view.addSubview(floaty)
// also tried: self.tabBarController?.view.addSubview(floaty)

I tried setting the margins like this:

floaty.layoutMargins = UIEdgeInsets(top: 0, left: 0, bottom: 60, right: 0)
floaty.layoutIfNeeded()
self.view.layoutIfNeeded()

But it doesn't work.

enter image description here

How do I correctly place the button in the table view controller? Or at least, how do I set the bottom margin programmatically?

EDIT:

Also tried

self.navigationController?.view.addSubview(floaty)

And at first it adds the button correctly, but when I switch tabs it reverts back to the position where is overlayed by the bottom bar. Here:

enter image description here enter image description here


Solution

  • This line of code will solve the padding problem:

    floaty.paddingY += tabBarController!.tabBar.frame.size.height
    

    If you want the fab to be global for all of your tabs, you should add it like here:

    tabBarController!.view.addSubview(floaty)
    

    Otherwise, if you add it to the navigationController and I assume that you have a different one for every tab, it will exist only in that navigationController's viewControllers. The same happens if you add it to self.view, because it will only exist in that view controller.

    Also, if you want to hide/unhide the fab in some specific view controllers, you should use a combination of viewWillAppear/viewDidAppear/viewWillDisappear/viewDidDisappear methods like here:

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        floaty.isHidden = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        floaty.isHidden = true
    }
    

    Good luck!