2014-09-24 24 views
0

我有一個帶有4個選項卡的標籤欄控制器。從我的3選項卡我有一個按鈕,帶你到其他日期選擇器的另一個視圖。我想通過完成按鈕將此日期返回到我的3選項卡,但不幸的是,數據不會返回。我發現這篇文章How to pass data back from one view to other View in IOS?如何將數據從視圖傳遞迴帶有完成按鈕的標籤欄控制器中的視圖

我可以回去但數據不傳輸。這裏是我的代碼:

NSDateFormatter *Format = [[NSDateFormatter alloc]init]; 
[Format setDateFormat:@"MMM dd, yyyy"]; 
NSString *Date = [Format stringFromDate:selectDate.date]; 
NSLog(Date); 
BookArtistViewController *parentView = (BookArtistViewController *)[self.tabBarController.viewControllers objectAtIndex:2]; 
parentView.Date = Date; 
[self.navigationController popViewControllerAnimated:YES]; 

謝謝你的幫助!

回答

1

爲什麼不使用AppDelegate?您可以在您的AppDelegate中創建一個日期屬性,然後爲其分配UiDatePicker日期。

在你AppDelegate.h創建屬性:

@property (strong, nonatomic) NSDate *myDate; 

在包含您的UIDatePicker進口AppDelegate.h視圖控制器然後在「完成」按鈕保存所選擇的日期爲指明MyDate:

#import "myViewController.h" 
#import "AppDelegate.h" 

@interface myViewController() 
@property (strong, nonatomic) IBOutlet UIDatePicker *myUIDatePicker; 
- (IBAction)saveDate:(id)sender; 
@end 

- (IBAction)saveDate:(id)sender { 
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
    appDelegate.myDate = self.myUIDatePicker.date; 
    NSLog(@"%@", appDelegate.myDate); 
} 

現在,在你的第三個標籤,導入AppDelegate.h,創建一個名爲dateLabel標籤和建立其屬性:

#import "myThirdTabViewController.h" 
#import "AppDelegate.h" 

@interface myThirdTabViewController() 
@property (strong, nonatomic) IBOutlet UILabel *dateLabel; 
@end 

,並把這個代碼在viewWillAppear中:

-(void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    dateFormatter.dateStyle = NSDateFormatterMediumStyle; 
    dateFormatter.timeStyle = NSDateFormatterShortStyle; 
    self.dateLabel.text = [dateFormatter stringFromDate:appDelegate.myDate]; 
} 

所選擇的日期將出現在標籤中。

+2

另一種選擇是創建一個單例來保存數據。我儘量避免向我的應用程序委託中添加任何內容,這與我的應用程序的生命週期無關。 – AdamPro13 2014-09-24 22:55:00

+0

謝謝你的想法! @Diego我想知道,我試過使用這段代碼,但它給了我一個錯誤,我需要導入它使其工作?我嘗試應用程序delegate.h但沒有運氣 – paul590 2014-09-25 16:41:24

+0

@AdamPro我將如何創建一個單一的共享兩個視圖?再次感謝你! – paul590 2014-09-25 16:42:26

相關問題