I created a subclass of UITabBarController on my iOS app because I wanted to add a middle "+" button on the tab bar. I added this extra button using the code below:
class XGTabBarViewController: UITabBarController {
let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 70, height: 70))
private let optionMenu = UIAlertController(title: nil, message: "New", preferredStyle: .actionSheet)
override func viewDidLoad() {
super.viewDidLoad()
let action1 = UIAlertAction(title: "Action 1", style: .default)
let action2 = UIAlertAction(title: "Action 2", style: .default)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
optionMenu.addAction(action1)
optionMenu.addAction(action2)
optionMenu.addAction(cancelAction)
var menuButtonFrame = menuButton.frame
let iconConfig = UIImage.SymbolConfiguration(pointSize: 24, weight: .medium, scale: .medium)
let iconImage = UIImage(systemName: "plus", withConfiguration: iconConfig)
let icon = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
icon.image = iconImage
icon.tintColor = UIColor.white
menuButtonFrame.origin.y = view.bounds.height - menuButtonFrame.height - 50
menuButtonFrame.origin.x = view.bounds.width/2 - menuButtonFrame.size.width/2
menuButton.frame = menuButtonFrame
menuButton.backgroundColor = UIColor(named: "LinkBlue")
menuButton.layer.cornerRadius = menuButtonFrame.height/2
menuButton.layer.shadowColor = UIColor.black.cgColor
menuButton.layer.shadowRadius = 3
menuButton.layer.shadowOpacity = 0.3
menuButton.layer.shadowOffset = CGSize(width: 0, height: 3)
menuButton.addSubview(icon)
icon.translatesAutoresizingMaskIntoConstraints = false
icon.widthAnchor.constraint(equalToConstant: 30).isActive = true
icon.heightAnchor.constraint(equalToConstant: 30).isActive = true
icon.centerXAnchor.constraint(equalTo: menuButton.centerXAnchor).isActive = true
icon.centerYAnchor.constraint(equalTo: menuButton.centerYAnchor).isActive = true
view.addSubview(menuButton)
menuButton.addTarget(self, action: #selector(menuButtonAction(sender:)), for: .touchUpInside)
view.layoutIfNeeded()
}
@objc private func menuButtonAction(sender: UIButton) {
self.present(optionMenu, animated: true, completion: nil)
}
I setup the tab bar controller via IB. And this is how it looks like
So, what I want know is if I should define the menu button action within this class? Or is there a better (best practice) way to do it?
As you can see, I tried to add an action sheet that will be shown when the button is tapped. But I am getting some layout errors. I am wondering if I added this code in the right place.
I am getting the error below:
Thanks!