How to Transfer Data between views in Xamarin iOS.

We have create a tutorial about how to go to one view to another but what about passing data between this views. In this tutorial we are going to extend our last tutorial , so if you didn’t look at it please refer it. We just pass segue push to transfer views in it.
To transfer data between views we need to override PrepareForSegue method. This method on the initial view controller and handling the data ourselves. When the segue is triggered – for example, with a button press – the application will call this method, providing an opportunity to prepare the new view controller beforeany navigation occurs.
First we are goin to add a label on second view controller and add it name as “lbl_data”. Create a UIViewController instance give it name as TransferView and assign it to second view controller. Also declare a string variable and give it name as data.
Now for root view controller create a UIViewController instance and name it as NavigationSegue and assign it to the root view controller.We are going to remane the button text as “Click here”.
Now in NavigationSegue write:
1 2 3 4 5 6 7 8 |
public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { base.PrepareForSegue (segue, sender); var transferdata = segue.DestinationViewController as TransferView; if (transferdata != null) { transferdata.data="Data from 1st view"; } } |
this PrepareForSegue method will pass data between our root view to second view by string variable we declared in file TransferView.
Now in TransferView write:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
partial class TransferView: UIViewController { public string data; public TransferView (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); lbl_data.Text = data; Console.WriteLine ("Data:"+data); } } |
And that’s all. Try to build and run the project and you will see string that you write on root view controller in second view like:
Leave a Reply