主要是選擇使用delegate的方式,
在ParentViewController.h
#import
#import "ChildViewController.h"
@interface ViewController : UIViewController<ChildViewControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *parentTF;
@end
ParentUIViewController .m 檔
#import "ViewController.h"
@interface ViewController ()
@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.
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:@"mySegue"])
{
ChildViewController *cVC = segue.destinationViewController;
cVC.delegate = self;
}
}
-(void) done:(NSString *)someText andChildBtn:(UIButton *)childBtn
{
self.parentTF.text = someText;
[childBtn setTitle:@"changed" forState:UIControlStateNormal];
[self.view setBackgroundColor:[UIColor darkGrayColor]];
}
@end
而在 ChildViewController.h 要宣告定義好protocol讓UIViewController能夠處理你要他做的事情
#import <UIKit/UIKit.h>
// 傳到到另個 ViewController ,所以自己要先定義protocol
@protocol ChildViewControllerDelegate <NSObject>
-(void)done:(NSString*)someText andChildBtn:(UIButton*)childBtn;
@end
@interface ChildViewController : UIViewController
@property(nonatomic,assign) id<ChildViewControllerDelegate> delegate;
@property (weak, nonatomic) IBOutlet UIButton *passValueBtn;
@property (weak, nonatomic) IBOutlet UITextField *childTF;
- (IBAction)passValueAction:(id)sender;
@end
然後.m檔去呼叫delegate方法
#import "ChildViewController.h"
@implementation ChildViewController
- (IBAction)passValueAction:(id)sender {
[self.delegate done:self.childTF.text andChildBtn:self.passValueBtn];
}
@end
這樣就可以透過container view controller去傳值給parentviewcontroller
而還有夠簡易的方式是
直接由container view controller去修改parent view controller的值
例如
((ViewController*)self.parentViewController).lb.text =[NSString stringWithFormat:@"%ld",indexPath.row];
以上是由container view 呼叫 parent view的屬性
沒有留言:
張貼留言