开发者

Passing of UITextField text from one view to another

开发者 https://www.devze.com 2023-03-31 17:08 出处:网络
I defined a UITextField on my firstViewController as follow // firstViewController.h IBOutlet UITextField *PickUpAddress

I defined a UITextField on my firstViewController as follow

// firstViewController.h
IBOutlet UITextField *PickUpAddress
@property (nonatomic, retain) UITextField *PickUpAddress;

//firstViewController.m
@synthesize PickUpAddress;

// Push secondView when the 'Done' keyboard button is pressed
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    if (textField == PickUpAddress) {
        SecondViewController *secondViewController= [[SecondViewController alloc]
                                                       initWithNibName:@"SecondViewController" 
                                                       bundle:nil];
        secondVie开发者_如何学PythonwController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:secondViewController animated:YES];
        [secondViewController release];
    }

    return NO;
}

Then I tried to retrive it in my secondViewController during viewWillAppear

- (void)viewWillAppear:(BOOL)animated {
    BookingViewController *bookingViewController = [[BookingViewController alloc] init];
    NSString *addressString = [[NSString alloc] init];
    addressString = bookingViewController.PickUpAddress.text;
    NSLog(@"addressString is %@", bookingViewController.PickUpAddress.text);
}

But it returns as NULL on my console. Why is that so? Thanks in advance :)


in secondViewController.h add

 NSString *text;

 @property (nonatomic, retain) NSString *text;

 -(void)setTextFromText:(NSString *)fromText;

in secondViewController.m add following

 - (void)setTextFromText:(NSString *)fromText
 {
     [text release]; 
     [fromText retain];
     text = fromText;
 }

in firstViewController.m before

[self.navigationController pushViewController:secondViewController animated:YES];

add

[secondViewContoller setTextFromText:PickUpAddress.text];

Now let me explain the code.

You are adding an NSString to second view , where we will store the text from the UITextField. Then, we've written a method, which will set that NSString from some other NSString. Before pushing secondViewController to navigationController, you're just calling that method to set our text from PickUpAddress.text. Hope that helped.


Problem is in your code. You are creating new object, bookingViewController, to retrieve the textField value. So it will obviously provide NULL. Rather you should use one unique object application wide to access the value.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号