【问题标题】:Make UIScrollView a first responder使 UIScrollView 成为第一响应者
【发布时间】:2013-02-11 17:43:13
【问题描述】:

我创建了一个准系统 iOS 应用程序,它向窗口添加了一个 UIScrollView(没有 ViewControllers 或 UIViews -- 我只是这样做是为了看看我是否能理解发生了什么。)

我只想让 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 对象报告为第一响应者。我确定我错过了一些非常简单的东西,对吧?

【问题讨论】:

    标签: objective-c cocoa-touch first-responder


    【解决方案1】:

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

    becomeFirstResponder 上的文档指出

    您可以调用此方法来使响应者对象(例如视图)成为第一响应者。但是,只有当它是视图层次结构的一部分时,您才应该在该视图上调用它。如果视图的 window 属性包含一个 UIWindow 对象,则它已安装在视图层次结构中;如果它返回 nil,则视图与任何层次结构分离。

    【讨论】:

    • 就是这样!我还没有把它放到层次结构中。我知道它必须是小东西。随时为我提供测试服务:P
    猜你喜欢
    • 2012-05-17
    • 2011-06-02
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 2018-02-17
    • 2012-09-22
    相关资源
    最近更新 更多