iosswiftuitabbarcontrolleruitoolbar

How to implement toolBar in tabBar?


I would like to implement a toolbar in my tab bar or ender my tab bar like in the photo app. I show you :

Tab Bar turn to when select button tapped Tool bar

I already try to put the toolbar in the Tab bar controller view, without success.

Thanks for your replies !


Solution

  • I believe this might be the sort of behaviour you're looking for. You don't have to use a custom UIButton you could use a UIBarButtonItem, but that's up to you, I just chose to demonstrate it with a custom UIButton to show you that this is one way of doing it.

    class ViewController: UIViewController {
        var selectButton: UIButton!
        var isInSelectMode = false
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            selectButton = UIButton(type: .system)
            selectButton.addTarget(self, action: #selector(selectButtonTapped), for: .touchUpInside)
            selectButton.setTitle("Select", for: .normal)
            view.addSubview(selectButton)
            
            let trashButton = UIBarButtonItem(barButtonSystemItem: .trash, target: nil, action: nil)
            toolbarItems = [trashButton]
            
            selectButton.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                selectButton.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor, constant: -15),
                selectButton.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: 15),
            ])
            
        }
        
        @objc func selectButtonTapped() {
            isInSelectMode = !isInSelectMode
            if isInSelectMode {
                selectButton.setTitle("Done", for: .normal)
                tabBarController?.tabBar.isHidden = true
                tabBarController?.tabBar.backgroundColor = .systemBackground
                navigationController?.setToolbarHidden(false, animated: true)
                
            } else {
                selectButton.setTitle("Select", for: .normal)
                tabBarController?.tabBar.isHidden = false
                tabBarController?.tabBar.backgroundColor = .clear
                navigationController?.setToolbarHidden(true, animated: true)
                
            }
            
        }
    
    }
    

    Here's what it looks like: demo gif of what the code does