swift如何通过解除当前的viewcontroller将数据推送到其他视图?

时间:2018-01-12 05:36:04

标签: ios uiviewcontroller segue

我正在尝试将一些数据从当前的视图控制器(我们称之为AViewController)推送回来(让我们称之为BViewController)

然而,当我使用performSegue方法时,它向我展示了我想要的AViewController但是让屏幕底部的标签栏控制器消失了(这是因为它使用performSegue方法创建了一个新的“视图”?)

但是当我使用dismiss方法时,没有数据被传回(在self.performSegue完成时都没有)

那么如何将我的数据推回到AViewController,同时仍然在底部有我的标签栏控制器?

这是我的代码

 // Push data to AViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    var aViewController = segue.destination as? AViewController
    if routineReps.isEmpty == false {
        for i in 0...routineReps.count-1 {
            routineViewController?.workOutNameArray.append(routineNames[i])
            routineViewController?.workOutSetsArray.append(routineSets[i])
            routineViewController?.workOutRepsArray.append(routineReps[i])
        }
    }
}

 // Button Action to push data back to previous viewcontroller
 @IBAction func completeAddingWorkoutButton(_ sender: UIButton) {

    self.performSegue(withIdentifier: "addWorkoutsForTodaySegue", sender: self)
 }

2 个答案:

答案 0 :(得分:2)

如上所述,您可以使用代表 NSNotificationCenter Singleton Patterm

场景是您从A类导航到B类,现在想要在返回A类时将数据从B类传递到A,您想要传递数据

 Class A -> Navigates -> Class B
       <- Sends Data back

代表 -

在B类中定义协议

BViewController类

 @objc
 protocol ClassBDelegate {
      func passingSomeValue(val : String)
  }

  class BViewController{
        weak var delegate : ClassBDelegate! //define a variable of the protocol
       func passValueWhenFromThisMethod(){
             let someString = "this value will get passed"
              delegate.passingSomeValue(someString)
              self.navigationController?.popViewController(animated: true)
        }
  }

类AViewController

  class AViewController{
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if let segue.identifier = "segueidentifierforgoingtoclassBVC"{
           var classBVC = segue.destinationViewController as! BViewController
             classBVC.delegate = self
       }
  }
   }

  extension AViewController : ClassBDelegate{
    func passingSomeValue(val : String){
         print("Got this value from Class B: \(val)")
     }
   }

答案 1 :(得分:0)

使用delegate按照以下链接中给出的方法将数据传递给之前的ViewController:

Passing data back from view controllers Xcode