View controller created manually from a storyboard in application:didFinishLaunching does not respond to touch events

StackOverflow https://stackoverflow.com/questions/21818041

Question

I want to create my storyboard manually in code rather than have it load automatically, so I first removed the launch storyboard in the plist like so:

enter image description here

With this in my app delegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    UIViewController * initalViewController = [storyboard instantiateInitialViewController];

    UIWindow *window = [[UIWindow alloc] init];
    [window setRootViewController:initalViewController];
    [window makeKeyAndVisible];

    self.window = window;

    return YES;
}

The initial view controller loads correctly and is visible, however it does not get any touch events. I even set a breakpoint on touchesBegan. Does anyone know why the touches are not being delivered?

Was it helpful?

Solution

You have created your window with no frame, which will mean it actually has a frame of {{0, 0}, {0, 0}}. Views can not receive touches that are outside of their parents bounds therefore with a zero frame everything is out of the windows bounds.

You should probably update to something like this

UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];

See the note from the UIWindow docs (emphasise my own)

Note:
When you use storyboards and the Xcode app templates to create an app, a window is created for you. If you choose to create a window in Interface Builder, be sure to select the Full Screen at Launch option in the Attributes inspector so that the window is sized appropriately for the current device. Because a window doesn’t receive touch events outside of its bounds and views aren’t clipped to the window’s bounds by default, an improperly sized window might not be able to deliver touch events to all its views.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top