如何将数据从UIViewController传递到UITabBarController?

时间:2018-02-04 13:23:53

标签: swift uiviewcontroller uitabbarcontroller

在UIViewController中:

class ViewController2: UIViewController {

    var points = 0

    var pressed = false

    @IBOutlet weak var label: UILabel!

    @IBAction func slider(_ sender: UISlider) {
        number = Int(sender.value)
        label.text = String(number)
    }

    @IBAction func submitbutton(_ sender: UIButton) {
        pressed = true
    }
}

如果按下UIViewController中的按钮,我会尝试在TabBarController中执行某些操作,并在另一个TabBarConroller中为该数字添加一个数字。

Image 1: This shows the connection between my ViewControllers.

Image 2: This shows the first two ViewControllers.)

Image 3: This shows the third and fourth ViewController

这是我的故事板。我用几句话来描述我想在图像中做些什么。如果您需要更清楚的描述,请告诉我。谢谢!

3 个答案:

答案 0 :(得分:0)

如果ViewController是您要访问的UITabBarController的子级,则只需使用tabBarController的{​​{1}}属性,例如,使用此属性进行更改选择控制器到第一个:

UIViewController

所以,让我们说你有一个自定义的@IBAction func submitbutton(_ sender: UIButton) { pressed = true self.tabBarController?.selectedIndex = 0 } 子类,例如:

UITabBarController

然后你可以按如下方式传递数据:

class CustomTabBarController: UITabBarController {


    func acceptData(points: Int) {
        print(">>> Accepted: \(points)")
        // or do anything you need to do with it
    }
}

<强>更新

由于似乎当前的VC由tabBarController子控制器之一呈现,您必须通过@IBAction func submitbutton(_ sender: UIButton) { pressed = true if let customTabController = self.tabBarController as? CustomTabBarController { customTabController.acceptData(points: self.points) } } 访问它:

self.presentingViewController

更新2

您的屏幕截图质量很差,您对此问题的解释也需要澄清,因为您很难理解您尝试做什么。所以在评论中的整个讨论之后,我猜这就是它:

@IBAction func submitbutton(_ sender: UIButton) {
    pressed = true
    if let customTabController = self.presentingViewController?.tabBarController as? CustomTabBarController {
        customTabController.acceptData(points: self.points)
    }
}

答案 1 :(得分:0)

TabBarController课程中,选择一个变量 variableToBeSet

class TabBarController: UITabBarController
{
    var variableToBeSet: Int = 0    // This is just an example. You can change it as per requirement.
    // Rest of class implementation
}

现在在ViewController

@IBAction func submitbutton(_ sender: UIButton) {
    pressed = true
    let tabControllerInstance = self.tabBarController as! TabBarController
    tabControllerInstance.variableToBeSet = localVariable    // The value which you want to assign
} 

答案 2 :(得分:0)

  

您可以正常传递数据

   let vc:HomeVC = ApiUtillity.sharedInstance.getCurrentLanguageStoryboard().instantiateViewController(withIdentifier: "HomeVC") as! HomeVC
   vc.tempCategoryArray = CategoryArray
   self.navigationController?.pushViewController(vc, animated: true)