Passing of UITextField text from one view to another

℡╲_俬逩灬. 提交于 2019-12-23 04:47:16

问题


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];
        secondViewController.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 :)


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7212908/passing-of-uitextfield-text-from-one-view-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!