iOS 响应点击(单击或双击)scrollview空白处事件 使用NSNotification

这篇博客介绍了如何在iOS应用中处理ScrollView的单击和双击事件,特别是当点击发生在空白区域时。通过创建一个自定义的UIScrollView子类,并在双击事件发生时发送NSNotification,然后在ViewController中注册该通知,实现对ScrollView事件的有效响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      我们时常需要在软件中点击空白处然后显示或者隐藏导航栏,工具栏,Tab时。如果 在UIView中这个很容易实现,将view的Custom Class 由UIVIew更改为UIControl,就可以发现View和Button一样拥有了事件响应,但是在UIScrollView中该方法就行不通了,这时就需要使用NSNotification在类与类之间实现通信。

  首先我们需要重写UIScrollView,也即继承它一下

  分别时头文件和.m文件

#import <UIKit/UIKit.h>

@interface myScrollView : UIScrollView{
    
}

@end

    在scrollview双击事件发生的时候发送notification,而且标识其为BNR(随便起个名字而已);

#import "myScrollView.h"

@implementation myScrollView

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
   
    UITouch *touch = [touches anyObject];
    if (2 == [touch tapCount]) {//响应双击事件
        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
        NSLog(@"nc send!");
        [nc postNotificationName:@"BNR" object:self];
        //发送notification消息
    }
}



@end

    在viewController类中注册一下,此前已经定义并且连接了myScrollView

   IBOutlet myScrollView *scrollView;

    注册一个notification

- (void)viewDidLoad{
    scrollView.contentSize = CGSizeMake(320, 1000);
    UIButton *bt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    bt.frame = CGRectMake(1, 0, 100, 50);
    [bt setTitle:@"Normal" forState:UIControlStateNormal];
    [scrollView addSubview:bt];
    
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self
           selector:@selector(doubleClicked) //响应scrollview被双击的函数
               name:@"BNR" object:nil];
    //注册notification
    NSLog(@"Observer!");
                    
}
    然后在另一个类中调用函数doubleClicked,这样就能在另一个类中响应scrollView被双击的事件了,加入相应代码就能实现显示或者隐藏导航栏和Tab的功能。

- (void)doubleClicked{
    NSLog(@"Succed to pass double click!");
    bShowNavAndTab = !bShowNavAndTab;
    self.navigationController.navigationBarHidden = bShowNavAndTab;
    NSArray *views = [self.tabBarController.view subviews];
    for (id v in views) {
        if ([v isKindOfClass:[UITabBar class]]) {
            [(UITabBar *) v setHidden:bShowNavAndTab];
        }
    }
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值