【发布时间】:2018-04-05 23:35:36
【问题描述】:
所以我正在尝试学习如何将数据从一个视图控制器发送到另一个视图控制器。
到目前为止,我的代码获取从一个 VC (DelegateVC) 输入的数据,并将其显示在另一个 VC (ViewController) 的标签中。
这里的委托是ViewController,委托是DelegateVC。
================================================ ==============================
主要问题
但是如果我想将标签的数据从ViewController 传递给DelegateVC 怎么办?我怎样才能做到这一点?我尝试设计相同的代表概念,但将DelegateVC 作为ViewController 的代表。不确定这是否是写方法。
TL;DR:
在VC,如果我点击Next View,我转到DelegateVC并输入“test”,它会在VC's receiving label中显示为“test”。
现在下次我点击Next View 时,我希望现有标签的值显示在DelegateVC 的TextField 中。将有值“test”,而不是空白的TextField。
================================================ ==============================
假设我有一个像这样的Main.storyboard:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
ViewController.m:
#import "ViewController.h"
#import "DelegatedVC.h"
@interface ViewController () <MainVCDelegate>
@property (strong, nonatomic) IBOutlet UILabel *receivingLabel;
- (IBAction)nextView:(id)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)nextView:(id)sender {
}
-(void) sendBackData:(DelegatedVC *)delegatedVC :(NSString *)textField {
[delegatedVC dismissViewControllerAnimated:YES completion:nil];
self.receivingLabel.text = textField;
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
DelegatedVC *secondVC = segue.destinationViewController;
secondVC.delegate = self;
}
@end
DelegateVC.h:
#import <UIKit/UIKit.h>
@protocol MainVCDelegate;
@interface DelegatedVC : UIViewController
@property (strong, nonatomic) IBOutlet UITextField *sendDataTF;
- (IBAction)sendData:(id)sender;
@property (weak, nonatomic) id<MainVCDelegate> delegate;
@end
@protocol MainVCDelegate <NSObject>
-(void) sendBackData: (DelegatedVC *) delegatedVC : (NSString *) textField;
@end
DelegateVC.m:
#import "DelegatedVC.h"
@protocol MainVCDelegate;
@interface DelegatedVC ()
@end
@implementation DelegatedVC
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)sendData:(id)sender {
[self.delegate sendBackData: self : _sendDataTF.text];
}
@end
【问题讨论】:
标签: ios objective-c iphone uiviewcontroller delegates