我成功地在容器视图中嵌入和交换uiviewcontrollers。现在我想从子uiviewcontrollers发送消息到父uivewcontroller。我将它们作为代理连接起来,但无法弄清楚如何在父视图中将其指定为委托
parent.h -load delegate
// Import child delegates
#import "GenWarnDangerVC.h"
@interface Appliance_IPVC : UIViewController <ChildViewControllerDelegate>
{
}
parent.m -load子视图
- (void)viewDidLoad
{
[super viewDidLoad];
// * Add child views
[self addChildViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"ChildFour"]];
[self addChildViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"ChildOne"]]; // <-- this is the delegate
[self addChildViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"ChildTwo"]];
[self addChildViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"ChildThree"]];
self.currentChildController = self.childViewControllers[0];
self.currentChildController.view.frame = self.containerView.bounds;
[self.containerView addSubview:self.currentChildController.view];
for (UIViewController *controller in self.childViewControllers)
[controller didMoveToParentViewController:self];
// Tried making it delegate here, complies but zilch happens
UIStoryboard *storyboard = self.storyboard;
GenWarnDangerVC *_GenWarnDangerVC = [storyboard instantiateViewControllerWithIdentifier:@"ChildOne"];
_GenWarnDangerVC.delegate=self;
}
我们稍后在运行时使用
进行切换[self transitionFromViewController:oldController toViewController:newController duration:0.33 options:options animations:^{} completion:nil];
childview.h - 委托设置内容
#import <UIKit/UIKit.h>
@protocol ChildViewControllerDelegate;
@interface GenWarnDangerVC : UIViewController <UITextViewDelegate>
@property (nonatomic, weak) id<ChildViewControllerDelegate> delegate;
@end
@protocol ChildViewControllerDelegate <NSObject>
- (void)animateTextField:(BOOL)up;
@end
childview.m - 向父母发送讯息
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView;
{
//if ([self.delegate respondsToSelector:@selector(animateTextField:)])
//{
// Sending delegate message
NSLog(@"Sending delegate message");
[self.delegate animateTextField:YES];
//}
return YES;
}
父视图永远不响应,它在父视图(本身)中调用时处理[self animateTextField:YES]但从未从子视图“听到”。
我猜是因为我们需要在父视图中告诉子视图谁是委托人,例如
UIStoryboard *storyboard = self.storyboard;
GenWarnDangerVC *_GenWarnDangerVC = [storyboard instantiateViewControllerWithIdentifier:@"ChildOne"];
_GenWarnDangerVC.delegate=se
LF;
但是(a)到底是什么? 并且(b)是否在加载cild视图时完成?或者他们被交换?
答案 0 :(得分:0)
问题在于我如何初始化子控制器
[self addChildViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"ChildOne"]];
这会加载控制器,但没有给自己留下引用,因此可以为其分配一个委托。
然而,这确实如此。耶。GenWarnDangerVC * GenWarnDanger_vc = [self.storyboard instantiateViewControllerWithIdentifier:@"ChildOne"];
[self addChildViewController:GenWarnDanger_vc];
GenWarnDanger_vc.delegate = self;