iOS中tabBar按鈕再次點擊實現界面回滾或刷新

下面是新浪微博示意圖
tabBar按鈕點擊.gif
  • 在這里說下實現思路

    • 首先是自定義tabBar,遍歷子控件,監聽按鈕的點擊事件
    • 在按鈕點擊事件方法中判斷按鈕是否為再次點擊,如果是對外發出通知
    • 在要實現的刷新或回滾的控制器中接收通知
    • 在對應的控制器中實現刷新或回滾
  • 下面直接上代碼

    • 自定義tabBar
      在ZBHTabBar.m中,在這里需要做的是判斷當前要點擊按鈕是否為上一個按鈕,如果是,再對外發出通知

#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];
}
  • 下面是UIView分類中的方法的實現
/** 判斷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);
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容