Question

I have created a barebones iOS application that adds a single UIScrollView to the Window (no ViewControllers or UIViews -- I just did this to see if I can understand what's going on.)

All I want is for the UIScrollView to be notified when the device is shaken.

I have subclassed UIScrollView to implement the canBecomeFirstResponder method:

#import "SampleScrollView.h"

@implementation SampleScrollView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

And in my AppDelegate I create an object of SampleScrollView, add to the Window, and then try to set it to first responder:

#import "SampleScrollView.h"

@implementation ResponderTestAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];


    // Override point for customization after application launch.

    CGRect thisFrame = [[self window] bounds];
    SampleScrollView *myScrollView = [[SampleScrollView alloc] initWithFrame:thisFrame];

    // Set scrollview to be the first responder
    BOOL success = [myScrollView becomeFirstResponder];
    if (success)
    {
        NSLog(@"myScrollView is first responder");
    }
    else
    {
        NSLog(@"Not first responder.");
    }

This is a highly simplified example, but for some reason I cannot get the application to report the SampleScrollView object as first responder. I'm sure I'm missing something very simple, right?

Était-ce utile?

La solution

In your example you are not adding the scroll view to any superview. Try adding this line [self.window addSubview: myScrollView]; before calling becomeFirstResponder.

The documentation on becomeFirstResponder states that

You may call this method to make a responder object such as a view the first responder. However, you should only call it on that view if it is part of a view hierarchy. 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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top