按钮显示选项卡
问题描述:
我在我的项目中获得了TabBarController
两个视图。现在我想在应用启动时设置一个FirstViewController
,其中两个按钮为Initial View Controller
。第一个按钮的TabBarController
应显示FirstView
,第二个按钮应显示第二个按钮。当两个按钮中的一个被按下时,FirstViewController
应该消失,并且应该只能在两个视图之间导航,其中TabBarViewController
中的选项卡。按钮显示选项卡
答
我做了一些小修改,并测试我写的代码和它的作品。控制从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
}
}
}
答
这可能是你想要的。
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
}
}
不要忘记设置你的UITabBarController
的Storyboard ID
。
您的意思是选项卡,而不是点击。 – rmaddy
您是否正在使用TabBarController来满足上述要求? – Vinodh
什么是更好的解决方案? –