單例---視圖間數據的傳遞:標簽顯示輸入的內容【多個視圖中】
阿新 • • 發佈:2017-07-05
release 視圖 pro button data- pos view copy field
ModalViewController.m
BackData.h
RootViewController.m
- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor greenColor]; //創建顯示文字的label UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 40)]; label.tag = 102; label.backgroundColor = [UIColor grayColor]; [self.view addSubview:label]; [label release]; //加入按鈕 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(20, 20, 90, 60); [button setTitle:@"打開模態" forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } - (void)viewWillAppear:(BOOL)animated { UILabel *label = (UILabel *)[self.view viewWithTag:102]; //創建單例對象 BackData *backData = [BackData shareData]; label.text = backData.text; [super viewWillAppear:animated]; } - (void)buttonAction { ModalViewController *modalCtrl = [[[ModalViewController alloc] init] autorelease]; modalCtrl.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; [self presentViewController:modalCtrl animated:YES completion:NULL]; }
#import "BackData.h" @interface ModalViewController () @end @implementation ModalViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor redColor]; //加入按鈕 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(20, 20, 90, 60); [button setTitle:@"關閉模態" forState:UIControlStateNormal]; [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; //創建輸入框 UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 100, 200, 40)]; textField.tag = 101; textField.borderStyle = UITextBorderStyleRoundedRect; [self.view addSubview:textField]; [textField release]; } - (void)buttonAction { UITextField *field = (UITextField *)[self.view viewWithTag:101]; //創建單例對象 BackData *data = [BackData shareData]; data.text = field.text; [self dismissViewControllerAnimated:YES completion:NULL]; }
BackData.h
@interface BackData : NSObject @property (nonatomic, copy) NSString *text; + (BackData *)shareData;
static BackData *data = nil; @implementation BackData + (BackData *)shareData { if (data == nil) { data = [[BackData alloc] init]; } return data; }
單例---視圖間數據的傳遞:標簽顯示輸入的內容【多個視圖中】