“奇怪”,我注意到以下行为:
ChildViewController
设置的背景颜色不会出现ChildViewController
添加了基本的点按手势识别器,但没有点击识别UIButton
会显示UIButton
,但在点击UIButton部分时没有响应在我的ParentViewController
中,我非常一般地展示ChildViewController
,如下所示:
UIViewController *viewController;
viewController = (ChildViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ChildViewController"];
[self addChildViewController:viewController];
viewController.view.frame = self.view.bounds;
viewController.view.translatesAutoresizingMaskIntoConstraints = NO;
viewController.view.center = self.view.center;
[self.view addSubview:viewController.view];
[self.view bringSubviewToFront:viewController.view];
[viewController didMoveToParentViewController:self];
以下是我在ChildViewController
的{{1}}中所做的一些非常基本的事情:
viewDidLoad
我确保所有内容都正确连接 - 但是,当我在模拟器或设备中点按它时self.view.backgroundColor = [UIColor yellowColor];
UIButton *tapButton = [UIButton buttonWithType:UIButtonTypeSystem];
[tapButton addTarget:self action:@selector(tappedOnTap) forControlEvents:UIControlEventTouchUpInside];
//button view customization code omitted for brevity
tapButton.userInteractionEnabled = YES;
tapButton.enabled = YES;
[self.view addSubview:tapButton];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedOnView)];
[self.view addGestureRecognizer:tapGesture];
[self.view setUserInteractionEnabled:YES];
[self.view addGestureRecognizer:tapGesture];
和tappedOnView
都没有确认。
我是否遗漏了一些关于提出tappedOnTap
修改
对于那些好奇的人来说,这个非常基本的应用程序在Github上。
答案 0 :(得分:1)
遏制电话很好。但是,如果您使用视图调试器(),则会发现frame
不正确。这是因为您已关闭translatesAutoresizingMaskIntoConstraints
,但您没有任何限制。您可以将其重新打开(并相应地设置autoresizingMask
):
viewController.view.translatesAutoresizingMaskIntoConstraints = true;
或者您可以定义约束而不是设置frame
(并冗余设置center
):
//viewController.view.frame = self.view.bounds;
viewController.view.translatesAutoresizingMaskIntoConstraints = false;
//viewController.view.center = self.view.center;
[self.view addSubview:viewController.view];
[NSLayoutConstraint activateConstraints:@[
[viewController.view.topAnchor constraintEqualToAnchor:self.view.topAnchor],
[viewController.view.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
[viewController.view.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor],
[viewController.view.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor]
]];
答案 1 :(得分:0)
试试这个:
ChildViewController *viewController;
viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ChildViewController"];
viewController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleheight;
[self addChildViewController:viewController];
[self.view addSubview:viewController.view];
[viewController didMoveToParentViewController:self];
除了那些基本方法之外,将ViewController添加到另一个时通常不需要做任何事情。由于视图会自动调整,您不需要设置所有这些属性,如大小和中心等...