我有一个关于代表团的问题。我对编程还很陌生,我刚刚管理了我使用委托的第一个练习项目。它就是一个父视图控制器,它调用一个子视图控制器,其中有一个文本字段和一个按钮。我在该文本字段中写了一些东西,按下按钮,子 VC 被关闭并将文本传回。然后它会显示在父级的标签中。我有几个动画过渡。这一切都有效。先上几张图和代码:
这是我的父视图控制器:
单击按钮,出现子项:
在文本字段中写一些东西,然后按按钮将其传回:
数据显示在父视图控制器的标签上。
以下是相关文件:
父视图控制器.h
#import <UIKit/UIKit.h>
#import "ChildViewController.h"
@interface ParentViewController : UIViewController <ChildViewControllerDelegate>
@property (strong, nonatomic) IBOutlet UILabel *label;
@end
父视图控制器.m
@implementation ParentViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)Pressed:(id)sender {
ChildViewController *childViewController = [[ChildViewController alloc]init];
[self displayContentController:childViewController];
childViewController.delegate = self;
}
- (void) displayContentController: (UIViewController*) content {
[self addChildViewController:content];
content.view.frame = CGRectMake(0, 115, 320, 240);
content.view.backgroundColor = [UIColor redColor];
CATransition *transition = [CATransition animation];
transition.duration = 1;
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromLeft;
[transition setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[content.view.layer addAnimation:transition forKey:nil];
[self.view addSubview:content.view];
[content didMoveToParentViewController:self];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void) passDataBack:(NSString *)data{
self.label.text = data;
}
@end
ChildViewController.h
#import <UIKit/UIKit.h>
@protocol ChildViewControllerDelegate <NSObject>
-(void)passDataBack:(NSString*)data;
@end
@interface ChildViewController : UIViewController
@property (strong, nonatomic) IBOutlet UITextField *txtfield;
@property (nonatomic, weak) id <ChildViewControllerDelegate> delegate;
- (IBAction)passingBack:(id)sender;
@property NSString *data;
@end
ChildViewController.m
#import "ChildViewController.h"
@interface ChildViewController ()
@end
@implementation ChildViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (IBAction)passingBack:(id)sender {
NSString *itemToPassBack = self.txtfield.text;
[self.delegate passDataBack:itemToPassBack];
[self.childViewControllers lastObject];
[self willMoveToParentViewController:nil];
[UIView animateWithDuration:1
delay:0.0
usingSpringWithDamping:1
initialSpringVelocity:1
options:UIViewAnimationOptionCurveEaseIn
animations:^{
self.view.frame = CGRectMake(-320, 115, 320, 240);
} completion:^(BOOL complete){
[self.view removeFromSuperview];
[self removeFromParentViewController];
}];
}
@end
关于代码,有几件事我不确定,因为我正在学习我复制了很多代码等......所以例如我不确定如何使用相同的方法为子控制器设置动画就像我曾经在其中设置动画一样,或者它是否重要以及最佳实践是什么等等......另外,我在控制台中收到一条奇怪的消息:“Interface Builder 文件中的未知类 ViewController”。但它有效,所以我不确定它为什么在那里。作为记录,我没有使用故事板,只有 xibs。
不过,我的问题如下:我希望有一个按钮来关闭子视图控制器,而不是在子视图控制器中,而是在父视图中,如下所示:
这就是我迷路的地方。我只是不知道如何触发从父视图控制器传回数据的方法。任何人都可以帮忙吗?非常感谢