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

来源:互联网 发布:网页游戏源码下载 编辑:程序博客网 时间:2024/04/30 04:50

      我们时常需要在软件中点击空白处然后显示或者隐藏导航栏,工具栏,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];        }    }}




原创粉丝点击