簡體   English   中英

將UITextField文本從一個視圖傳遞到另一個視圖

[英]Passing of UITextField text from one view to another

我在我的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。 為什么會這樣? 提前致謝 :)

在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設置我們的文本。 希望有所幫助。

問題在於您的代碼。 您正在創建新對象bookingViewController,以檢索textField值。 所以它顯然會提供NULL。 相反,您應該使用一個唯一的對象應用程序來訪問該值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM