首页 > 解决方案 > 如何从 UITabBar 导航到另一个视图控制器?

问题描述

如何从 UITabBar 导航到另一个视图控制器?我正在研究 UITabBarController。谁有 4 个 TabBar 按钮,我在 UITabBar 中间添加了一个大按钮。所以我想在单击大中间按钮时导航到新的 viewController。

在此处输入图像描述

实际上我在这里添加了大按钮子类化 UITabBar()。我给你 UITabBar() 的所有代码所以请告诉我我该怎么做。现在一切正常,但只有 Navigateto 新的视图控制器不工作。

import UIKit

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)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        middleButton.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: 0)
    }

    func setupMiddleButton() {
        middleButton.frame.size = CGSize(width: 70, height: 70)
        middleButton.backgroundColor = .blue
        middleButton.layer.cornerRadius = 35
        middleButton.layer.masksToBounds = true
        middleButton.setTitle("+", for: .normal)
        middleButton.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: 0)
        middleButton.addTarget(self, action: #selector(largeButtonAction), for: .touchUpInside)
        addSubview(middleButton)
    }

    @objc func largeButtonAction(_ sender:UIButton) {
        print("Write your Navigation Code here.......")
       jumpToHomeVC()
    }
    
    
    func jumpToHomeVC(){
        let story = UIStoryboard(name: "Main", bundle:nil)
        let vc = story.instantiateViewController(withIdentifier: "HomeVC") as! HomeVC
        let nav = UINavigationController(rootViewController: vc)
        nav.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    
}


我将我的 UITabBar() 子类化为我的自定义 MainTabBar()。

在此处输入图像描述

我想当我点击大按钮时转到新的 UIViewController 和当再次点击返回时来到 UITabBarController 意味着关闭或 PopViewController。

或者如果有任何其他解决方案可以在 UItabBarController 的中间创建一个大按钮。单击按钮中的任意位置以跳转到新的 ViewController 并在关闭时返回上一个控制器。

标签: iosswiftuitabbarcontrollerswift4swift5

解决方案


推荐阅读