将UITextField文本从一个视图传递到另一个视图

时间:2011-08-27 06:32:33

标签: iphone uitextfield

我在firstViewController上定义了一个UITextField,如下所示

// 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中检索它
- (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。为什么会这样? 在此先感谢:)

2 个答案:

答案 0 :(得分:2)

在secondViewController.h中添加

 NSString *text;

 @property (nonatomic, retain) NSString *text;

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

在secondViewController.m中添加以下

 - (void)setTextFromText:(NSString *)fromText
 {
     [text release]; 
     [fromText retain];
     text = fromText;
 }
在firstViewController.m中

之前

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

添加

[secondViewContoller setTextFromText:PickUpAddress.text];

现在让我解释一下代码。

您正在向第二个视图添加NSString,我们将在其中存储UITextField中的文本。然后,我们编写了一个方法,该方法将从其他NSString中设置NSString。 在将secondViewController推送到navigationController之前,您只需调用该方法从PickUpAddress.text设置我们的文本。 希望有所帮助。

答案 1 :(得分:0)

问题在于您的代码。您正在创建新对象bookingViewController,以检索textField值。所以它显然会提供NULL。相反,您应该使用一个唯一的对象应用程序来访问该值。

相关问题