Passing Data in Swift

前端 未结 3 826
遇见更好的自我
遇见更好的自我 2020-12-07 22:06

I have been looking for an answer for this, but have only found answers for segues.

I have viewController1 with a button that segues to viewContr

3条回答
  •  伪装坚强ぢ
    2020-12-07 22:45

    (Swift 2.1, Xcode 7, iOS9) If you don't want it to be tightly coupled only between 2 ViewControllers, You can also use the Notification Design Pattern (Post & Observe), which is mainly used to pass on the same object/information from one VC to multiple View Controllers.

    For your scenario : In VC2.swift :

    @IBAction func BackBtn(sender: UIButton) {  
      NSNotificationCenter.defaultCenter().postNotificationName("ThisIsTheMessage", object: nil, userInfo:["ObjectBeingSent":yourObject])
    
    }
    

    And in VC1.swift :

    override func viewDidLoad() {
            super.viewDidLoad()
            NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("yourFunction:"), name: "ThisIsTheMessage", object: nil)
        }
    
    
    
    func yourFunction(theNotification : NSNotification) {
    
               if let extractInfo = theNotification.userInfo {
         //code to use the object sent from VC2, by extracting the object details
        }
         }
    

    Common Practise is:

    1. Pass data forward -> Use PrepareForSegue
    2. Pass data backward to the previous View Controller-> Protocol and Delegation
    3. Pass data across multiple View Controllers -> Notifications : Post and Observe(observe in all the View controllers where you are using the object details)

提交回复
热议问题