iOS UIButton在编程实例化的子视图中没有触发 [英] iOS UIButton in programatically instantiated subview not firing
问题描述
我的故事板中有一个Nib,它与任何东西都没有关联,但我实际上将它作为子视图实例化:
I have a Nib in my storyboard which is not connected to anything but I'm instantiating it as a subview thusly:
-(void)LoadCameraOverlayView
{
CameraOverlayViewController *cameraVC = [self.storyboard instantiateViewControllerWithIdentifier:@"CameraOverlayNib"];
cameraVC.view.userInteractionEnabled = YES;
[self.view addSubview:cameraVC.view];
}
UIViewController有一个反馈相机,工作正常,还有一个按钮(当我转向视图控制器也工作正常。)
The UIViewController has a camera with feedback which is working fine and a button which (when I segue to the view controller also works fine.)
该按钮链接到Touch Down事件和Touch Up Inside事件。
The button is linked to a Touch Down event and Touch Up Inside event.
当我点击按钮时,我可以看到它在视觉上从默认状态变为聚焦状态或突出显示状态,但似乎没有任何代码正在执行。如果我在ViewDidLoad中放置一个NSLog,我可以在控制台中看到它,但不能在链接方法中看到。但是,如果我认为它确实有效。
When I click the button I can see it is changing visually from its default state to its focused or highlighted state however none of the code seems to be executing. If I put an NSLog in the ViewDidLoad I can see that in the console but not for the linked method. However if I segue to the view it does work.
任何想法发生了什么?
我看了其他解决方案,但我不认为可能是存在视图或CGRect未正确校准或任何事情,因为我可以看到单击按钮时的视觉变化。
I looked at other solutions but I don't think it could be that there is a view in the way or that the CGRect isn't calibrated correctly or anything since I can see the visual change when clicking the button.
谢谢。
推荐答案
此代码违反规则1如何使用视图控制器:
This code violates Rule One of how to use view controllers:
CameraOverlayViewController *cameraVC = [self.storyboard instantiateViewControllerWithIdentifier:@"CameraOverlayNib"];
[self.view addSubview:cameraVC.view];
您不能简单地实例化视图控制器,然后手动将其视图添加到视图层次结构中。对此有非常严格的规定;你必须做一个精心设计的舞蹈才能手动为你的界面添加一个视图控制器的视图,而你却没有跳舞。
You cannot simply instantiate a view controller and then add its view manually to the view hierarchy like that. There are very strict rules about this; there is an elaborate "dance" that you must do in order to add a view controller's view to your interface manually, and you are not doing the dance.
结果是您的 cameraVC
成立,在视图控制器层次结构中没有任何位置,并在一阵烟雾中消失。因此没有任何对象可以让您的按钮与之交谈,因此当点击该按钮时,没有任何反应。
The result is that your cameraVC
comes into existence, is given no place in the view controller hierarchy, and vanishes in a puff of smoke. There is thus no object for your button to talk to, and so when the button is tapped, nothing happens.
我的建议是:使用 .xib此视图的文件,而不是故事板场景;在加载并将其放入界面后,使用代码配置按钮,使其与 self
,当前视图控制器对话。
My suggestion would be: use a .xib file, not a storyboard scene, for this view; and after you have loaded it and put it into the interface, use code to configure the button so that it talks to self
, your current view controller.
这篇关于iOS UIButton在编程实例化的子视图中没有触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!