2

In my view controller I have initialized a new UIView Subclass called HypnosisView and added it to the root view of the ViewController. And in viewDidLoad I set the view to become the first responder like so:

- (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:

- (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."

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!

Nearpoint
  • 7,202
  • 13
  • 46
  • 74
  • What is the value of `[view2 isFirstResponder]` before you call `becomeFirstResponder`? – bneely Sep 21 '13 at 23:52
  • I just checked an before I call becomeFirstResponder the value of [view2 isFirstResponder] is nil. Also I checked after the call becomeFirstResponder and it was still nil. Really confusing. – Nearpoint Sep 22 '13 at 00:04
  • From the documentation: If the view’s window property holds a UIWindow object, it has been installed in a view hierarchy; if it returns nil, the view is detached from any hierarchy. I just checked an view2.window == nil. How can I add this view to the view Hierarchy? I add view2 as a subview to the main view of the HypnosisViewController. And in App Delegate I set the rootviewControllerto be HypnosisViewController. – Nearpoint Sep 22 '13 at 00:05
  • In the app delegate I even tried this with no luck: [self.window addSubview:controller.view2]; – Nearpoint Sep 22 '13 at 00:11
  • 1
    What if you make view2 a property or instance variable of your controller, then handle the firstResponder business in the -viewDidAppear: method instead of -viewDidLoad? – bneely Sep 22 '13 at 00:31
  • That worked, if you make your comment an answer I will vote it up! Thanks so much! Just so I know, how come it worked in viewDidAppear instead of in viewDidLoad? Thanks again, you fixed my issue that was drivin me crazy! – Nearpoint Sep 22 '13 at 01:01

1 Answers1

1

Make view2 a property within your UIViewController. Create view2 and add it to the subview in -viewDidLoad, but set it as the first responder in -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.

bneely
  • 9,083
  • 4
  • 38
  • 46