我有一个带有 4 个选项卡的选项卡栏 Controller 。在我的 3 选项卡中,我有一个按钮,可以将您带到另一个带有日期选择器的 View 。我想通过完成按钮将此日期返回到我的 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];
感谢您的帮助!
最佳答案
为什么不使用AppDelegate?您可以在 AppDelegate 中创建日期属性,然后将 UiDatePicker 日期分配给它。
在您的 AppDelegate.h 中创建属性:
@property (strong, nonatomic) NSDate *myDate;
在包含 UIDatePicker 的 View Controller 中导入 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 );
}
现在,在您的第 3 个 TAB 中,导入 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];
}
所选日期将出现在标签中。
关于ios - 如何使用完成按钮将数据从 View 传回选项卡栏 Controller 中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26027422/