Tabbarcontroller Adding Custom Button Not Clickable Issue

Make custom button on Tab Bar rounded

Solution

You need to subclass UITabBarController and then add the button above TabBar's view. A button action should trigger UITabBarController tab change by setting selectedIndex.

Code

The code below only is a simple approach, however for a full supporting iPhone (including X-Series)/iPad version you can check the full repository here: EBRoundedTabBarController

class CustomTabBarController: UITabBarController {

// MARK: - View lifecycle

override func viewDidLoad() {
super.viewDidLoad()

let controller1 = UIViewController()
controller1.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 1)
let nav1 = UINavigationController(rootViewController: controller1)

let controller2 = UIViewController()
controller2.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 2)
let nav2 = UINavigationController(rootViewController: controller2)

let controller3 = UIViewController()
let nav3 = UINavigationController(rootViewController: controller3)
nav3.title = ""

let controller4 = UIViewController()
controller4.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 4)
let nav4 = UINavigationController(rootViewController: controller4)

let controller5 = UIViewController()
controller5.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 5)
let nav5 = UINavigationController(rootViewController: controller5)

viewControllers = [nav1, nav2, nav3, nav4, nav5]
setupMiddleButton()
}

// MARK: - Setups

func setupMiddleButton() {
let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64))

var menuButtonFrame = menuButton.frame
menuButtonFrame.origin.y = view.bounds.height - menuButtonFrame.height
menuButtonFrame.origin.x = view.bounds.width/2 - menuButtonFrame.size.width/2
menuButton.frame = menuButtonFrame

menuButton.backgroundColor = UIColor.red
menuButton.layer.cornerRadius = menuButtonFrame.height/2
view.addSubview(menuButton)

menuButton.setImage(UIImage(named: "example"), for: .normal)
menuButton.addTarget(self, action: #selector(menuButtonAction(sender:)), for: .touchUpInside)

view.layoutIfNeeded()
}

// MARK: - Actions

@objc private func menuButtonAction(sender: UIButton) {
selectedIndex = 2
}
}

Output

Sample Image

the best way to add custom button on tabbar center

The problem of your first option is that it's not hiding ? If so, you can hide it manually.

Custom tabbar button does not work

It seems that 'self` is a tab bar controller. Change:

self.tabBarController.selectedIndex = 2;

to

self.selectedIndex = 2;


Related Topics



Leave a reply



Submit