Created
July 20, 2020 17:04
-
-
Save codertcet111/f5b27a0f366e1ea61fa37c1865b8f907 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Here's a little help on delegates between two view controllers: | |
#Step 1: Make a protocol in the UIViewController that you will be removing/will be sending the data. | |
protocol FooTwoViewControllerDelegate:class { | |
func myVCDidFinish(_ controller: FooTwoViewController, text: String) | |
} | |
#Step2: Declare the delegate in the sending class (i.e. UIViewcontroller) | |
class FooTwoViewController: UIViewController { | |
weak var delegate: FooTwoViewControllerDelegate? | |
[snip...] | |
} | |
#Step3: Use the delegate in a class method to send the data to the receiving method, which is any method that adopts the protocol. | |
@IBAction func saveColor(_ sender: UIBarButtonItem) { | |
delegate?.myVCDidFinish(self, text: colorLabel.text) //assuming the delegate is assigned otherwise error | |
} | |
#Step 4: Adopt the protocol in the receiving class | |
class ViewController: UIViewController, FooTwoViewControllerDelegate {} | |
#Step 5: Implement the delegate method | |
func myVCDidFinish(_ controller: FooTwoViewController, text: String) { | |
colorLabel.text = "The Color is " + text | |
controller.navigationController.popViewController(animated: true) | |
} | |
#Step 6: Set the delegate in the prepareForSegue: | |
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { | |
if segue.identifier == "mySegue" { | |
let vc = segue.destination as! FooTwoViewController | |
vc.colorString = colorLabel.text | |
vc.delegate = self | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment