У меня есть пользовательские классы для моего UITabBar и моего UITabBarController.Пользовательский UITabBar определяет кнопку, которая при нажатии должна открывать правильную вкладку в TabBar.Однако я не могу получить правильный код для открытия вкладки.
Как получить доступ к своему пользовательскому UITabBarController для изменения вкладки, или в противном случае текущая вкладка может быть изменена непосредственно из UITabBar?
class MainTabBar: UITabBar {
private var middleButton = UIButton()
override func awakeFromNib() {
super.awakeFromNib()
setupMiddleButton()
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if self.isHidden {
return super.hitTest(point, with: event)
}
let from = point
let to = middleButton.center
return sqrt((from.x - to.x) * (from.x - to.x) + (from.y - to.y) * (from.y - to.y)) <= 39 ? middleButton : super.hitTest(point, with: event)
}
func setupMiddleButton() {
middleButton.frame.size = CGSize(width: 70, height: 70)
middleButton.backgroundColor = .white
middleButton.layer.borderWidth = 2
middleButton.layer.borderColor = self.tintColor.cgColor
if let image = UIImage(named: "create") {
middleButton.setImage(image, for: .normal)
}
middleButton.layer.cornerRadius = 35
middleButton.layer.masksToBounds = true
middleButton.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: 0)
middleButton.addTarget(self, action: #selector(click), for: .touchUpInside)
addSubview(middleButton)
}
@objc func click() {
}
}
И контроллер:
class CustomTabBarController: UITabBarController {
let button = UIButton.init(type: .custom)
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
}
}
extension CustomTabBarController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
guard let index = viewControllers?.index(of: viewController) else {
return false
}
if index == 4 {
let alert = UIAlertController(title: "What do you need?", message: "Please choose between Support and Training", preferredStyle: .actionSheet)
let action1 = UIAlertAction(title: "Support", style: .default) { (action:UIAlertAction) in
tabBarController.selectedIndex = 0
ChoiceStruct.choice = "support"
tabBarController.selectedIndex = 4
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction) in
// Do nothing
}
let action3 = UIAlertAction(title: "Training", style: .default) { (action:UIAlertAction) in
tabBarController.selectedIndex = 0
ChoiceStruct.choice = "training"
tabBarController.selectedIndex = 4
}
alert.addAction(action1)
alert.addAction(action2)
alert.addAction(action3)
present(alert, animated: true, completion: nil)
return false
}
return true
}
}
Цель состоит в том, чтобы получить доступ к tabBarController.selectedIndex из моего класса MainTabBar, чтобы изменить выбранную вкладку