简体   繁体   中英

How can I do this in Swift? (My version don't working)

I have problem with join navigator controller and containerView. I want if I click button in ViewController, the view in TabViewController must change on other view. (I know, haven't code to change view, but i want first print this log.) TabBarViewController is embedded in ContainerView. TabViewController is rootView NavigationController.

So I created this:

在此处输入图像描述

And this is not working, when click a button I don't see text "this is test" in log.

This is my swift code:

import UIKit

class TabBarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

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

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        print("this is test");
    }

}

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    @IBAction func click1(_ sender: Any) {
        navigationController?.performSegue(withIdentifier: "segue1", sender: self)
    }
}

If I got your question right, you want to change the index of your TabBarController on click of the button in ViewController. Correct me if i am wrong.

Give the segue connecting your ViewController and TabBarController an identifier.

Then in your ViewController , declare this

var yourTabBarController : UITabBarController?

Then in your prepareForSegue method of ViewController ,

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "yourTabBarControllerSegue" {
        if let tabBarController = segue.destination as? UITabBarController {
                self.yourTabBarController = tabBarController
        }
    }
}

and lastly, on button press:

   @IBAction func yourButtonPressed(_ sender : Any) {
        if yourTabBarController?.selectedIndex == 0 {
            yourTabBarController?.selectedIndex = 1
        } else {
            yourTabBarController?.selectedIndex = 0
        }
    }

The ViewController you are trying to performSegue doesn't seem to have a navigationController . Try performSegue without the navigationController , like this:

@IBAction func click1(_ sender: Any) {
    performSegue(withIdentifier: "segue1", sender: nil)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM