让UIScrollView的第一反应

问题描述:

我创建了一个准系统iOS应用,将单个的UIScrollView到窗口(无ViewControllers或UIViews - 我只是做这个,看看我能理解这是怎么回事。)让UIScrollView的第一反应

所有我想要的是在设备震动时通知UIScrollView。

我有子类的UIScrollView实现canBecomeFirstResponder方法:

#import "SampleScrollView.h" 

@implementation SampleScrollView 

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

- (BOOL)canBecomeFirstResponder 
{ 
    return YES; 
} 

在我的AppDelegate我创造SampleScrollView的对象,添加到窗口,然后尝试将其设置为第一响应:

#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."); 
    } 

这是一个非常简化的例子,但由于某种原因,我无法让应用程序将SampleScrollView对象报告为第一响应者。我确信我错过了很简单的事情,对吧?

在您的示例中,您并未将滚动视图添加到任何超级视图。在致电becomeFirstResponder之前,尝试添加此行[self.window addSubview: myScrollView];

becomeFirstResponder的文档指出

您可能会调用该方法做出响应者的物体,如视图中的第一响应者。但是,如果是视图层次结构的一部分,则只能在该视图上调用它。如果视图的window属性包含一个UIWindow对象,则它已安装在视图层次结构中;如果它返回nil,则该视图将从任何层次结构中分离出来。

+1

就是这样!我还没有把它放到层次结构中。我知道它必须是小事。在我去的时候为我提供测试的权利:P – 2013-02-11 19:53:34