2016-10-22 134 views
0

我在我的项目中获得了TabBarController两个视图。现在我想在应用启动时设置一个FirstViewController,其中两个按钮为Initial View Controller。第一个按钮的TabBarController应显示FirstView,第二个按钮应显示第二个按钮。当两个按钮中的一个被按下时,FirstViewController应该消失,并且应该只能在两个视图之间导航,其中TabBarViewController中的选项卡。按钮显示选项卡

picture of the project

+1

您的意思是选项卡,而不是点击。 – rmaddy

+0

您是否正在使用TabBarController来满足上述要求? – Vinodh

+0

什么是更好的解决方案? –

回答

0

我做了一些小修改,并测试我写的代码和它的作品。控制从firstButton拖到TabBarController并选择Kind作为“Show”。然后用secondButton做同样的事情。 在与两个按钮你的看法,我首先把它叫做:

import Foundation 
import UIKit 

class First: UIViewController { 

    var firstWasClicked = false 
    @IBAction func firstButtonAction(sender: UIButton) { 
     firstWasClicked = true 
    } 

    @IBAction func secondButtonAction(sender: UIButton) { 
     firstWasClicked = false 
    } 


    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     let controller = segue.destinationViewController as! TabBarController 
     controller.firstSelected = firstWasClicked 
    } 
} 

然后在TabBarController:

import Foundation 
import UIKit 

class TabBarController: UITabBarController { 

    var firstSelected = true 
    override func viewDidLoad() { 
     if(firstSelected) { 
      self.selectedIndex = 0 
     } 
     else { 
      self.selectedIndex = 1 
     } 
    } 

}

+0

此代码实际上不起作用。 –

+0

它现在可以(测试) – DevB2F

+0

你可以请粘贴在你的项目中,你试过。 –

0

这可能是你想要的。

class ViewController: UIViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 

    // Do any additional setup after loading the view. 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

@IBAction func didTapFirst(button: UIButton) { 
    showViewControllerAt(index: 0) 
} 

@IBAction func didTapSecond(button: UIButton) { 
    showViewControllerAt(index: 1) 
} 

func showViewControllerAt(index: NSInteger) { 
    let tabBarController = self.storyboard?.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController 
    tabBarController.selectedIndex = index 
    UIApplication.shared.keyWindow?.rootViewController = tabBarController 
} 
} 

不要忘记设置你的UITabBarControllerStoryboard ID