Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

swift - Change the tabs in a Embedded TabBarController

I have a view controller which has two buttons and an embedded TabBarController. I want to use the two button instead of the tab bar item. And for some reason cannot make it work.

MainView

import UIKit

class ViewController: UIViewController {
    
    var currentTab = 0
    
    @IBOutlet weak var container: UIView!
    
    @IBAction func item1Button(_ sender: UIButton) {
        currentTab = 0
    }
    
    @IBAction func item2Button(_ sender: UIButton) {
        currentTab = 1
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toControllers"{
            if let vc = segue.destination as? TabsViewController {
                vc.selectedIndex = currentTab

            }
        }
    }
}

TabBarController

import UIKit

class TabsViewController: UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

I have two items in the storyboard, so item 0 and 1 should be ok.

Maybe it is very simple, cannot figure it out myself.

Thank you!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I figure it out, here is the solution:

Changed the main controller to:

class ViewController: UIViewController {
    
    var currentTab = 1
    private var tabViewController: UITabBarController?
    
    @IBOutlet weak var container: UIView!
    
    @IBAction func item1Button(_ sender: UIButton) {
        print("click item1")
        tabViewController?.selectedIndex = 0
    }
    
    @IBAction func item2Button(_ sender: UIButton) {
        print("click item2")
        tabViewController?.selectedIndex = 1
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toControllers"{
            if let vc = segue.destination as? TabsViewController {
                tabViewController = vc
            }
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...