简体   繁体   English

子视图不会成为第一响应者

[英]Subview will not become first responder

In my view controller I have initialized a new UIView Subclass called HypnosisView and added it to the root view of the ViewController. 在我的视图控制器中,我初始化了一个名为HypnosisView的新UIView子类,并将其添加到ViewController的根视图中。 And in viewDidLoad I set the view to become the first responder like so: 在viewDidLoad中,我将视图设置为第一响应者,如下所示:

- (void)viewDidLoad
{
    [super viewDidLoad];
    HypnosisView *view2 = [[HypnosisView alloc] initWithFrame:[[self view] bounds]];
    [self.view addSubview:view2];

    BOOL success = [view2 becomeFirstResponder];
    if (success) {
        NSLog(@"HypnosisView became the first responder");
    } else {
        NSLog(@"Could not become first responder");
    }
}

I also overrode the method canBecomeFirstResponder in the UIView HypnosisView.m file like so: 我还覆盖了UIView HypnosisView.m文件中的canBecomeFirstResponder方法,如下所示:

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

Now when I run the program I am expecting the console to report "HypnosisView became the first responder" but it reports "Could not become first responder." 现在,当我运行该程序时,我希望控制台报告“ HypnosisView成为第一响应者”,但报告“无法成为第一响应者”。

BUT

when I shake the device the view does respond to the shake event! 当我摇动设备时,视图确实响应摇动事件! So it looks like it actually became the first responder but it is reporting it did not become first responder. 因此,看起来它实际上已成为第一响应者,但它报告它并未成为第一响应者。 Such a strange issue, please help! 如此奇怪的问题,请帮忙!

Make view2 a property within your UIViewController. 将view2设置为UIViewController中的一个属性。 Create view2 and add it to the subview in -viewDidLoad , but set it as the first responder in -viewDidAppear: . 创建view2并将其添加到-viewDidLoad的子视图中,但将其设置为-viewDidAppear:的第一响应者。 I am not certain of this, but I assume the UIViewController's view has to appear before it or any of its subviews can become first responder. 我不确定,但是我认为UIViewController的视图必须先出现,否则它的任何子视图都可以成为第一响应者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM