事件机制

事件机制效果图

效果图 Gif.gif

AppDelegate.h

#import "AppDelegate.h"
#import "ButtonHitTestViewController.h"
#import "ButtonPointInsideViewController.h"
#import "ButtonSubViewOutsideViewController.h"
#import "KeyboardViewController.h"
#import "TestWindow.h"

@interface AppDelegate ()<UITableViewDataSource, UITableViewDelegate>
{
    UITableViewController *_tableVC;
}
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    _tableVC = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
    _tableVC.tableView.delegate = self;
    _tableVC.tableView.dataSource = self;
    _tableVC.edgesForExtendedLayout = UIRectEdgeNone;
    _tableVC.navigationItem.title = @"Touch2 Demo";
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:_tableVC];
    
    TestWindow *testWindow = [[TestWindow alloc] init];
    self.window = testWindow;
    self.window.rootViewController = nav;
    self.window.backgroundColor = [UIColor whiteColor];
    
    [self.window makeKeyAndVisible];
    
    return YES;

}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    NSString *title;
    switch (indexPath.row) {
        case 0:
            title = @"Button - hitTest";
            break;
        case 1:
            title = @"Button - pointInside";
            break;
        case 2:
            title = @"Button - subView outside";
            break;
        case 3:
            title = @"keyboard";
            break;
        default:
            break;
    }
    cell.textLabel.text = title;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UIViewController *targetVC;
    switch (indexPath.row) {
        case 0:
            targetVC = (UIViewController *)[[ButtonHitTestViewController alloc] init];
            break;
        case 1:
            targetVC = (UIViewController *)[[ButtonPointInsideViewController alloc] init];
            break;
        case 2:
            targetVC = (UIViewController *)[[ButtonSubViewOutsideViewController alloc] init];
            break;
        case 3:
            targetVC = (UIViewController *)[[KeyboardViewController alloc] init];
            break;
        default:
            break;
    }
    
    if (targetVC)
    {
        [_tableVC.navigationController pushViewController:targetVC animated:YES];
    }
    
}


@end

ButtonHitTestView.m

#import "ButtonHitTestView.h"

static const CGFloat buttonExtraPadding = 20;

@interface ButtonHitTestView()
{
    UIView *_buttonBgView; 
    UIButton *_button;
}
@end

@implementation ButtonHitTestView

- (instancetype)init {
    if (self = [super init]) {
        self.backgroundColor = [UIColor lightGrayColor];
        _buttonBgView = [[UIView alloc] init];
        _buttonBgView.layer.borderColor = [UIColor redColor].CGColor;
        _buttonBgView.layer.borderWidth = 1;
        [self addSubview:_buttonBgView];
        
        _button = [[UIButton alloc] init];
        [_button setBackgroundColor:[UIColor orangeColor]];
        [_button setTitle:@"button" forState:UIControlStateNormal];
        [_button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_button];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    _button.frame = CGRectMake(50, 50, 100, 30);
    
    _buttonBgView.frame = CGRectMake(_button.frame.origin.x - buttonExtraPadding, _button.frame.origin.y - buttonExtraPadding, _button.frame.size.width + buttonExtraPadding * 2, _button.frame.size.height + buttonExtraPadding * 2);
}

- (void)buttonClicked:(id)sender {
    //弹窗 alertView:
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定么?!" message:@"按钮 已经被点击" preferredStyle:UIAlertControllerStyleAlert];
    //alertView 下面的确定按钮:
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
    //弹出 alertVC:
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}


#pragma mark - 重写 hitTest 方法 - 扩展按钮范围
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    //给出一个我想要的扩大后的按钮的范围,这里用到了 CGRectGetMinX , CGRectGetMinY , CGRectGetWidth , CGRectGetHeight 等函数方法简化了代码:
    CGRect targetRect = CGRectMake(CGRectGetMinX(_button.frame) - buttonExtraPadding, CGRectGetMinY(_button.frame) - buttonExtraPadding, CGRectGetWidth(_button.frame) + buttonExtraPadding * 2, CGRectGetHeight(_button.frame) + buttonExtraPadding * 2);
    
    
    //这个方法就相当于上面的代码 , 扩大自身2倍的 dx 和2倍的 dy 同时还能让左上角点 orign 偏移:
    targetRect = CGRectInset(_button.frame, - buttonExtraPadding, - buttonExtraPadding);
    
    
    //判断我当前点击的目标范围在不在这个 targetRect 范围内:
    if (CGRectContainsPoint(targetRect, point)) {
        //如果在点击范围内,那么它就相当于点击了_ button 这个 view 视图: , ( UIButton --> UIControl --> UIView )
        return _button;
    }
    //如果不是的话我就交给原有的 super 方法去执行原有的 hitTest 方法逻辑:
    return [super hitTest:point withEvent:event];
}

@end

ButtonHitTestViewController.m

#import "ButtonHitTestViewController.h"
#import "ButtonHitTestView.h"

@implementation ButtonHitTestViewController

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.navigationItem.title = @"Button HitTest";
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    ButtonHitTestView *view = [[ButtonHitTestView alloc] init];
    [self.view addSubview:view];
    view.frame = CGRectMake(50, 50, 200, 200);
}

@end

ButtonPointInsideView.m

#import "ButtonPointInsideView.h"
#import "TestButton.h"


const static CGFloat buttonExtraPadding = 20;

@interface ButtonPointInsideView() {
    UIView *_buttonBgView; 
    TestButton *_button;
}

@end


@implementation ButtonPointInsideView

#pragma mark - init
- (instancetype)init {
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor lightGrayColor];
        
        _buttonBgView = [[UIView alloc] init];
        _buttonBgView.layer.borderColor = [UIColor redColor].CGColor;
        _buttonBgView.layer.borderWidth = 1;
        [self addSubview:_buttonBgView];
        
        _button = [[TestButton alloc] init];
        [_button setBackgroundColor:[UIColor orangeColor]];
        [_button setTitle:@"button" forState:UIControlStateNormal];
        [_button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_button];
    }
    return self;
}


#pragma mark - layoutSubviews
- (void)layoutSubviews {
    [super layoutSubviews];
    
    _button.frame = CGRectMake(50, 50, 100, 30);
    
    _buttonBgView.frame = CGRectMake(
                                     _button.frame.origin.x - buttonExtraPadding,
                                     _button.frame.origin.y - buttonExtraPadding,
                                     _button.frame.size.width + buttonExtraPadding*2,
                                     _button.frame.size.height + buttonExtraPadding*2
                                     );
}


#pragma mark - buttonClicked:
- (void)buttonClicked:(id)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"button clicked" preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}


@end

ButtonPointInsideViewController.m

#import "ButtonPointInsideViewController.h"
#import "ButtonPointInsideView.h"

@implementation ButtonPointInsideViewController

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.navigationItem.title = @"Button PointInside";
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    ButtonPointInsideView *view = [[ButtonPointInsideView alloc] init];
    [self.view addSubview:view];
    view.frame = CGRectMake(50, 50, 200, 200);
}


@end

TestButton.h

#import "TestButton.h"

@implementation TestButton

//判断当前点击的这个点是否在试图范围内的方法?!
//#pragma mark - 重写pointInside: withEvent: 方法
//- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
//{
//    CGFloat buttonExtraPadding = 20;
//    
//    //way1
////    CGRect targetRect = CGRectInset(self.bounds, - buttonExtraPadding, - buttonExtraPadding);
////    if (CGRectContainsPoint(targetRect, point))
////    {
////        return YES;
////    }
//    
//    //way2
//    CGPoint convertPoint = [self convertPoint:point toView:self.superview];
//    CGRect targetRect = CGRectInset(self.frame, - buttonExtraPadding, - buttonExtraPadding);
//    if (CGRectContainsPoint(targetRect, convertPoint))
//    {
//        return YES;
//    }
//    return [super pointInside:point withEvent:event];
//    
//}


//用 bounds 的方法:
//#pragma mark - 方法1
//- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
//    CGFloat buttonExtraPadding = 20;
//    CGRect targetRect = CGRectInset(self.bounds, - buttonExtraPadding, - buttonExtraPadding);
//    if (CGRectContainsPoint(targetRect, point)) {
//        return YES;
//    }
//    return [super pointInside:point withEvent:event];
//}


//还可以用 frame 的方式去判断, frame 与 bounds 的区别, frame 是按钮在父控件的坐标位置
#pragma mark - 方法2
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    CGFloat buttonExtraPadding = 20;
    //将当前坐标系转换到父视图的坐标系上:
    CGPoint convertPoint = [self convertPoint:point toView:self.superview];
    CGRect targetRect = CGRectInset(self.frame, -buttonExtraPadding, -buttonExtraPadding);
    if (CGRectContainsPoint(targetRect, point)) {
        return YES;
    }
    return [super pointInside:point withEvent:event];
}


@end

ButtonSubViewOutsideView.h

#import "ButtonSubViewOutsideView.h"

const static CGFloat buttonExtraPadding = 20;

@interface ButtonSubViewOutsideView()
{
    UIButton *_button;

}

@end

@implementation ButtonSubViewOutsideView
- (instancetype)init {
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor lightGrayColor];
        
        _button = [[UIButton alloc] init];
        [_button setBackgroundColor:[UIColor orangeColor]];
        [_button setTitle:@"button" forState:UIControlStateNormal];
        [_button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_button];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    _button.frame = CGRectMake(50, - buttonExtraPadding, 100, 30);
}


#pragma mark - 按钮点击方法
- (void)buttonClicked:(id)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"button clicked" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
    
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
}

//点击超出父视图的按钮位置的时候首先在父视图调用  pointInset 方法,发现点击位置不在父视图范围内,则返回 NO, 所以超出父视图范围不会响应按钮点击方法 , 重写 pointInset 方法 , 不是对 button 的 pointInset 方法修改,而是修改父视图的 pointInset 方法 , 让父视图的感知范围扩大
//#pragma mark - 重写pointInside方法判断点击位置是否在父视图范围内
//- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
//    if ([_button pointInside:[self convertPoint:point toView:_button] withEvent:event]) {
//        return YES;
//    }
//    return [super pointInside:point withEvent:event];
//}


- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    //当我点击的这个位置在 button 的范围内的时候就让父视图的 pointInset 返回 YES 即可!
    //转换到 button 的坐标系上,这里不能直接写 point , 因为直接写是 button 的位置相对于父视图的位置,现在是要转换到 button 的位置!!!
    if ([_button pointInside:[self convertPoint:point toView:_button] withEvent:event]) {
        return YES;
    }
    return [super pointInside:point withEvent:event];
}


@end

ButtonSubViewOutsideViewController.h

#import "ButtonSubViewOutsideViewController.h"
#import "ButtonSubViewOutsideView.h"

@implementation ButtonSubViewOutsideViewController

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.navigationItem.title = @"Subview OutSide";
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    ButtonSubViewOutsideView *view = [[ButtonSubViewOutsideView alloc] init];
    [self.view addSubview:view];
    view.frame = CGRectMake(50, 50, 200, 200);
}


@end

TestWindow.m

#import "TestWindow.h"

@implementation TestWindow

- (void)sendEvent:(UIEvent *)event {
    BOOL needEnd = YES;
    //遍历所有的 touches , 去除文本框里的位置, 文本框里的位置为第一响应位置!!!
    for (UITouch *touch in event.allTouches) {
        if ([touch.view isFirstResponder]) {
            needEnd = NO;
            break;
        }
    }
    
    if (needEnd)
    {
        [self endEditing:YES];
    }
    [super sendEvent:event];
}

@end

KeyboardViewController.h

#import "KeyboardViewController.h"
#import "KeyboardView.h"

@implementation KeyboardViewController

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        self.navigationItem.title = @"Keyboard";
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    KeyboardView *view = [[KeyboardView alloc] init];
    [self.view addSubview:view];
    view.frame = CGRectMake(50, 50, 200, 200);

}

@end

KeyboardView.h

#import "KeyboardView.h"

@interface KeyboardView() {
    UITextField *_textField;
}

@end

@implementation KeyboardView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setBackgroundColor:[UIColor lightGrayColor]];
        
        _textField = [[UITextField alloc] init];
        [_textField setBackgroundColor:[UIColor whiteColor]];
        [self addSubview:_textField];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    _textField.frame = CGRectMake(20, 50, 150, 30);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //way1
    //[_textField resignFirstResponder];
    
    //way2 UIView,收起键盘 分类方法 , 结束编辑
    //[self endEditing:YES];
    
    //way3 方法父视图的范围,让 window 去做 endEditing;
    //[[UIApplication sharedApplication].keyWindow endEditing:YES];
    
    //way4
    //用 UIApplication 的事件机制 , 通过 sendAction 沿着时间的响应链进行传递:
    //找到当前的第一响应 firstResponder , 然后调用该第一响应的 resignFirstResponder 方法:
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    
}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容