【问题标题】:create a tab bar to an already existing view controller?为已经存在的视图控制器创建一个标签栏?
【发布时间】:2018-06-14 03:36:31
【问题描述】:

我在 swift 中一直在没有故事板的情况下进行编程。通过这样做,我认为将标签栏添加到我的视图控制器会很有趣。我一直在研究不同的方法来尝试这个,但是,我还没有找到适合我的应用程序的答案。

    //This is my app delegate

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()
    let mainController = UINavigationController(rootViewController:       mainViewController())
    let loginController = UINavigationController(rootViewController: LoginController())

    FirebaseApp.configure()
    userIsloggedIn = defaults.bool(forKey: "User is Logged In")
    if userIsloggedIn == true {
      window?.rootViewController = mainController
    } else {
       window?.rootViewController = loginController
    }
    UINavigationBar.appearance().barTintColor = GREEN_Theme
    return true
}

//这是我的 TabBar 控制器,它位于我的“mainViewController”之上

类 CustomTabBarController: UITabBarController {

override func viewDidLoad() {
    super.viewDidLoad()

    self.tabBar.barTintColor = GREEN_Theme
    self.tabBar.isTranslucent = true
    self.tabBar.tintColor = .white

    let mainController = UINavigationController(rootViewController: mainViewController())
    mainController.tabBarItem.title = "Find Jobs"
    mainController.tabBarItem.image = UIImage(named: "job-search")
    let settingsController = UINavigationController(rootViewController: settingsViewController())
    settingsController.tabBarItem.title = "Settings"
    settingsController.tabBarItem.image = UIImage(named: "settings")
    let notificationsController = UINavigationController(rootViewController: notificationsViewController())
    notificationsController.tabBarItem.title = "Notifications"
    notificationsController.tabBarItem.image = UIImage(named: "notification")
    let messagesController = UINavigationController(rootViewController: messagesViewController())
    messagesController.tabBarItem.title = "Messages"
    messagesController.tabBarItem.image = UIImage(named: "chat")
    let historyController = UINavigationController(rootViewController: jobhistoryViewController())
    historyController.tabBarItem.title = "Job History"
    historyController.tabBarItem.image = UIImage(named: "medical-history")


    viewControllers = [historyController, notificationsController, mainController, messagesController, settingsController]
    return

}
}

// 最后,这是我的 mainViewController

import UIKit

导入基础 导入 Firebase 导入 MapKit 导入谷歌地图 导入核心位置

主视图控制器类:UIViewController、MKMapViewDelegate、CLLocationManagerDelegate {

private var locationManager = CLLocationManager()
var mapView = GMSMapView()
var camera = GMSCameraPosition()
var sidebarView: SidebarView!
var blackScreen: UIView!

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
    let lastLocation = locations[locations.count-1]
    if lastLocation.horizontalAccuracy>0{
        locationManager.stopUpdatingLocation()
        let latitude = lastLocation.coordinate.latitude
        let longitude = lastLocation.coordinate.longitude

    }
}

override func viewDidLoad() {
    super.viewDidLoad()



    let btnMenu = UIBarButtonItem(image: #imageLiteral(resourceName: "menu-button-of-three-horizontal-lines"), style: .plain, target: self, action: #selector(btnMenuAction))
    btnMenu.tintColor=UIColor(red: 54/255, green: 55/255, blue: 56/255, alpha: 1.0)
    self.navigationItem.leftBarButtonItem = btnMenu

    sidebarView=SidebarView(frame: CGRect(x: 0, y: 0, width: 0, height: self.view.frame.height))
    sidebarView.delegate=self
    sidebarView.layer.zPosition=100
    self.view.isUserInteractionEnabled=true
    self.navigationController?.view.addSubview(sidebarView)

    blackScreen=UIView(frame: self.view.bounds)
    blackScreen.backgroundColor=UIColor(white: 0, alpha: 0.5)
    blackScreen.isHidden=true
    self.navigationController?.view.addSubview(blackScreen)
    blackScreen.layer.zPosition=99
    let tapGestRecognizer = UITapGestureRecognizer(target: self, action: #selector(blackScreenTapAction(sender:)))
    blackScreen.addGestureRecognizer(tapGestRecognizer)
}

@objc func btnMenuAction() {
    blackScreen.isHidden=false
    UIView.animate(withDuration: 0.3, animations: {
        self.sidebarView.frame=CGRect(x: 0, y: 0, width: 250, height: self.sidebarView.frame.height)
    }) { (complete) in
        self.blackScreen.frame=CGRect(x: self.sidebarView.frame.width, y: 0, width: self.view.frame.width-self.sidebarView.frame.width, height: self.view.bounds.height+100)
    }
}

@objc func blackScreenTapAction(sender: UITapGestureRecognizer) {
    blackScreen.isHidden=true
    blackScreen.frame=self.view.bounds
    UIView.animate(withDuration: 0.3) {
        self.sidebarView.frame=CGRect(x: 0, y: 0, width: 0, height: self.sidebarView.frame.height)
    }
}

}

extension mainViewController: SidebarViewDelegate {
    func sidebarDidSelectRow(row: Row) {
        blackScreen.isHidden=true
        blackScreen.frame=self.view.bounds
        UIView.animate(withDuration: 0.3) {
            self.sidebarView.frame=CGRect(x: 0, y: 0, width: 0, height: self.sidebarView.frame.height)
        }
        switch row {
        case .editProfile:
            let vc=EditProfileVC()
            self.navigationController?.pushViewController(vc, animated: true)
        case .reviews:
            print("Reviews")
        case .contact:
            print("Contact")
        case .payment:
            print("Payment")
        case .share:
            print("Share")
        case .help:
            print("Help")
        case .signOut:
            print("Sign out")
            let SignOutvc=signoutVC()
            self.navigationController?.pushViewController(SignOutvc, animated: true)
        case .none:
            break
        }
        GMSServices.provideAPIKey("AIzaSyBDOLisA3c-wDTbkbSssAxEb3iLw7Y5vHo")
        let camera = GMSCameraPosition.camera(withLatitude: 40.001850, longitude: -83.019405, zoom: 17)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        self.view = mapView
        mapView.isMyLocationEnabled = true



    let currentLocation = CLLocationCoordinate2DMake(40.001850, -83.019405)
    let marker = GMSMarker(position: currentLocation)
    marker.snippet = "Current Location"
    marker.map = mapView
    self.mapView.addSubview(mapView)


    func getLocation(){
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

    }

    navigationController?.navigationBar.prefersLargeTitles = false
    navigationItem.title = "Welcome To Odd Jobs"
    navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 25)]
}
        func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
            reverseGeocodeCoordinate(position.target) // sending data when the mapView is not moved or pinched by the finger //
        }

        func reverseGeocodeCoordinate(_ coordinate: CLLocationCoordinate2D) {
            let geocoder = GMSGeocoder()
            geocoder.reverseGeocodeCoordinate(coordinate) { response, error in
                guard let address = response?.firstResult(), let _ = address.lines else {
                    return
    }
   }
  }
}

我的目标是将 customTabBarViewController 与我的主视图控制器结合起来。如果我运行我的应用程序,它会将我设置为 customTabBar,它与我的 mainVC 重叠。如果我注销并尝试登录,我将被放置在具有黑色背景的默认 tabBar 屏幕上。

【问题讨论】:

    标签: ios swift uiviewcontroller uitabbarcontroller


    【解决方案1】:

    不清楚您的问题是什么。您说由于您的登录,您不想将UITabBarController 添加为rootViewController,但是在您的示例中,您给出了解决方案,即根据登录来设置要设置的视图控制器。(连同登录后再次调用该条件。)

    但是直接回答您的问题,如果您想将UITabBarController 添加到UIViewController,您应该使用包含。

    // Adding a contained view controller
    addChildViewController(tabBarController)
    view.addSubview(tabBarController.view)
    tabBarController.didMove(toParentViewController: self)
    
    // Removing a contained view controller
    tabBarController.willMove(toParentViewController: nil)
    tabBarController.view.removeFromSuperview()
    tabBarController.removeFromParentViewController()
    

    【讨论】:

    • 抱歉这个误导性问题!我可以将它添加到 rootview 中,但我担心我会在不知道如何解决问题的情况下让我的应用程序崩溃!
    • 您可以更改根视图,它不会崩溃。如果您沿着这条路线走,您还可以使用动画进行更自然的变化。 stackoverflow.com/questions/41144523/…
    • 我的主视图控制器和登录视图控制器都设置为我的主根。与那个原因发生冲突?
    • 一次只能设置一个。您当前想要的应该是最新的一组。也不要害怕潜在的崩溃。 A. 尝试是最好的学习方式。 B. 您将不必在网上询问,从而节省时间。 C. 你的手机不会爆炸!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    相关资源
    最近更新 更多