UIKit 框架之UIResponder

时间:2024-11-22 09:06:25

前面博客有讲触摸事件提过响应事件和响应者链,而管理响应者链的正是UIResponder。

一、代码

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    NSLog(@"window:%@",[self.window nextResponder]);
    NSLog(@"AppDelegate: %@",[self nextResponder]);
    return YES;
}
//
//  ViewController.m
//  UIResponder
//
//  Created by cyw on 15-5-16.
//  Copyright (c) 2015年 cyw. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITextFieldDelegate>

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    UITextField *textField=[[UITextField alloc]init];
    textField.frame=CGRectMake(100, 100, 100, 40);
    textField.borderStyle=UITextBorderStyleLine;
    textField.backgroundColor=[UIColor redColor];
    textField.delegate=self;
    textField.tag=10001;
    BOOL canBecomeFirstResponder=[textField canBecomeFirstResponder     ];
    BOOL canResignFirstResponder=[textField canResignFirstResponder];
    NSLog(@"%d  %d",canBecomeFirstResponder,canResignFirstResponder);
    [textField becomeFirstResponder];
    [self.view addSubview:textField];

    UITextField *textField1=[[UITextField alloc]init];
    textField1.frame=CGRectMake(100, 200, 100, 40);
    textField1.borderStyle=UITextBorderStyleLine;
    textField1.backgroundColor=[UIColor redColor];
    textField1.delegate=self;
    textField1.tag=10002;
    [self.view addSubview:textField1];

     UIResponder *responder1= [textField nextResponder];
     UIResponder *responder2=[self nextResponder];
     UIResponder *responder3=[self.view nextResponder];
     NSLog(@"textField:%@\nViewController:%@\nself.view:%@",responder1,responder2,responder3);

}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
       BOOL isFirstResponder= [textField isFirstResponder];
        NSLog(@"textField%d isFirstResponder %d:",textField.tag,isFirstResponder);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

二、结果

2015-05-17 00:30:02.427 UIResponder[1132:60b] window:<UIApplication: 0x8d71b80>
2015-05-17 00:30:02.437 UIResponder[1132:60b] AppDelegate: (null)
2015-05-17 00:30:02.446 UIResponder[1132:60b] 1  1
2015-05-17 00:30:02.449 UIResponder[1132:60b] textField:<UIView: 0x8e742d0; frame = (0 0; 320 480); autoresize = RM+BM; layer = <CALayer: 0x8e739e0>>
ViewController:(null)
self.view:<ViewController: 0x8c9b8c0>
2015-05-17 00:30:02.463 UIResponder[1132:60b] textField10001 isFirstResponder 1:

三、由上面的输出结果有一点比较纳闷,为什么ViewController返回的是NULL?我想了半天也没想到什么原因,也请高手给指点一下

四、其实UIResponder不仅仅只有这些,具体可以参考:http://southpeak.github.io/blog/2015/03/07/uiresponder/?utm_source=tuicool