iOS高质量博客ios进阶ios 开发

iOS中tabBar按钮再次点击实现界面回滚或刷新

2016-04-03  本文已影响4538人  小虎哥
下面是新浪微博示意图
tabBar按钮点击.gif

#import "ZBHTabBar.h"

@interface ZBHTabBar ()

/** 记录上一次被点击按钮的tag */
@property (nonatomic, assign) NSInteger previousClickedTag;

@end

@implementation ZBHTabBar

//在layoutSubvews布局子控件
- (void)layoutSubviews{
    [super layoutSubviews];

    //遍历子控件
    NSInteger i = 0;
    for (UIButton *tabbarButton in self.subviews) {
        if ([tabbarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
           //绑定tag 标识
            tabbarButton.tag = i;
            i++;
            
            //监听tabbar的点击.
            [tabbarButton addTarget:self action:@selector(tabbarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    
}
#pragma mark -- tabbar按钮的点击
- (void)tabbarButtonClick:(UIControl *)tabbarBtn{
    //判断当前按钮是否为上一个按钮
    if (self.previousClickedTag == tabbarBtn.tag) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:
@"TabbarButtonClickDidRepeatNotification" object:nil];
    }
    self.previousClickedTag = tabbarBtn.tag;
}

@end
- (void)viewDidLoad {
    [super viewDidLoad];
    //接收通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabbarButtonClick) name:@"TabbarButtonClickDidRepeatNotification" object:nil];
}

在这里需要判断当前的视图是否在窗口上,我创建了UIView的分类用来实现的,后面会附上代码

#pragma mark -- 通知按钮的点击
- (void)tabbarButtonClick{
    
    //判断window是否在窗口上
    if (self.view.window == nil) return;
    //判断当前的view是否与窗口重合  nil代表屏幕左上角
    if (![self.view hu_intersectsWithAnotherView:nil]) return;
    //刷新
    [self.tableView.mj_header beginRefreshing];
}

同样的在需要回滚的控制器(如新浪 发现 界面)接收通知,在接收通知方法实现回滚

- (void)tabbarButtonClick{
    
    //判断window是否在窗口上
    if (self.view.window == nil) return;
    //判断当前的view是否与窗口重合
    if (![self.view hu_intersectsWithAnotherView:nil]) return;
    //实现界面的回滚
    [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
}
/** 判断self和anotherView是否重叠 */
- (BOOL)hu_intersectsWithAnotherView:(UIView *)anotherView
{

    //如果anotherView为nil,那么就代表keyWindow
    if (anotherView == nil) anotherView = [UIApplication sharedApplication].keyWindow;
    
    
    CGRect selfRect = [self convertRect:self.bounds toView:nil];

    CGRect anotherRect = [anotherView convertRect:anotherView.bounds toView:nil];
    
    //CGRectIntersectsRect是否有交叉
    return CGRectIntersectsRect(selfRect, anotherRect);
}
上一篇下一篇

猜你喜欢

热点阅读