将UITextField文本从一个视图传递到另一个视图 [英] Passing of UITextField text from one view to another
问题描述
我在firstViewController上定义了一个UITextField,如下所示:
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;
}
然后我试图在viewWillAppear期间在我的secondViewController中检索它
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);
}
但是它在我的控制台上返回为NULL.为什么? 在此先感谢:)
But it returns as NULL on my console. Why is that so? Thanks in advance :)
推荐答案
在secondViewController.h中添加
in secondViewController.h add
NSString *text;
@property (nonatomic, retain) NSString *text;
-(void)setTextFromText:(NSString *)fromText;
在secondViewController.m中添加以下内容
in secondViewController.m add following
- (void)setTextFromText:(NSString *)fromText
{
[text release];
[fromText retain];
text = fromText;
}
在firstViewController.m中
in firstViewController.m before
[self.navigationController pushViewController:secondViewController animated:YES];
添加
[secondViewContoller setTextFromText:PickUpAddress.text];
现在让我解释一下代码.
Now let me explain the code.
您正在向第二个视图添加NSString,我们将在其中存储UITextField中的文本.然后,我们编写了一个方法,该方法将从其他NSString中设置该NSString. 在将secondViewController推入navigationController之前,您只是调用该方法以从PickUpAddress.text设置我们的文本. 希望能有所帮助.
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.
这篇关于将UITextField文本从一个视图传递到另一个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!