我为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
}
}
目的是从MainTabBar类中访问tabBarController.selectedIndex,以更改所选的标签
答案 0 :(得分:0)
我发现最好的解决方案是将按钮的代码移到UITabBarController上,而不是为此目的而有一个自定义的UITabBar类