Ramkumar chintala
Ramkumar chintala

Reputation: 958

How do I show UITextField data on a UILabel in a second UIViewController in swift?

I'd like to pass through the data entered into the UITextFields in the current view controller to a second view controller on the save button action. I'm using storyboards, could anyone advise me on how to achieve this? I'm using Xcode 6.

@IBAction func SAVEButtonTapped(sender: AnyObject) {

    let viewcontroller = SecondViewController();
    viewcontroller.name = self.nametextfield.text;
    viewcontroller.phone = self.phonetextfield.text;
    viewcontroller.city = self.citytextfield.text;

}

Upvotes: 1

Views: 453

Answers (4)

Ramkumar chintala
Ramkumar chintala

Reputation: 958

I found my Problem

@IBAction func SAVEButtonTapped(sender: AnyObject) {

let viewcontroller = SecondViewController();
viewcontroller.name = self.nametextfield.text;
viewcontroller.phone = self.phonetextfield.text;
viewcontroller.city = self.citytextfield.text;

}

problem with this line let viewcontroller = SecondViewController()

i changed it to

let viewcontroller = self.storyboard!.instantiateViewControllerWithIdentifier("SecondViewController") as! SecondviewController

With This change My code working fine thanks..

Upvotes: 2

Dharma
Dharma

Reputation: 3013

pass the data between VC create a intent for destination VC,like below

SecondViewController *controller = [[SecondViewController alloc]  initWithNibName:@"SecondViewController" bundle:nil];
    viewcontroller.name = self.nametextfield.text;
    viewcontroller.phone = self.phonetextfield.text;
    viewcontroller.city = self.citytextfield.text;
 [self.navigationController pushViewController:controller animated:YES];

Upvotes: 0

Edward L.
Edward L.

Reputation: 564

What you are doing will not work because your views will not be initialized until viewDidLoad: is executed. Basically, you're assigning values to nil objects.

You either need to add string properties that you later assign to your view elements in viewDidLoad or do what Akhilrajtr mentioned if you are using a segue for your transition.

Upvotes: 0

Akhilrajtr
Akhilrajtr

Reputation: 5182

Try this in FirstViewController,

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    UIViewController *destinationVC = [segue destinationViewController];
    If ([destinationVC isKindOfClass:[SecondViewController class]]) {

        SecondViewController *viewcontroller = (SecondViewController *)destinationVC;
        viewcontroller.name = self.nametextfield.text;
        viewcontroller.phone = self.phonetextfield.text;
        viewcontroller.city = self.citytextfield.text;
    }
}

Assuming that you have only one segue to SecondViewController. If you have multiple segue to SecondViewController then you can check segue identifier instead of isKindOfClass check.

Upvotes: 0

Related Questions