BFScrollMenu-滑動時可操作View的Category

最近看到越來越多的App里出現了一種比較流行的UI設計,就是在Scrolling View(尤其是TableView)的上方出現一個menu view,這個View會隨著滑動的操作進行變化,最常見的變化就是,上滑時隱藏菜單,下滑時展示菜單。所以就嘗試著擴展UIViewController寫了一個BFScrollMenu的category,用來提供一個通用的,創建隨著滑動操作而進行變化的框架。

具體代碼地址在這里:GitHub - BFScrollMenu

思路

整個代碼很簡單,只有1個.h和1個.m文件。核心思想是借鑒了MJRefresh的做法,

  1. 使用Method swizzling將用戶常規的scrollview delegate method 替換成BFScrolling method
  2. 使用AssociatedObject動態關聯對象給UIViewController增加必要的成員屬性
  3. 在滑動時對操作進行判斷處理
  4. 提供滑動時的ActionBlock和滑動停止時的StopAction,并且提供額外的對action進行與判斷的conditionBlock。

使用方法很簡單,只需要在代理Class中(一般為實現scrolling delegate的ViewController)進行初始化設定即可:
- (void)setUpDelegateClass:(Class _Nonnull)delegateClass
MenuView:(UIView * _Nonnull )menuView
conditionBlock:(BFConditionBlock _Nullable)condition
scrollActionBlock:(BFActionBlock _Nullable)scrollAction
stopActionBlock:(BFActionBlock _Nullable)stopAction;

Example:

在UIViewController中:
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 21, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
// ... Create your own table view
[self.view addSubview:self.tableView];

    // Config the menu view to be manipulated ... 
    self.menuView = [[UIView alloc] initWithFrame:CGRectMake(0, 21, [UIScreen mainScreen].bounds.size.width, 80)];
    // ...
    [self.view addSubview:self.menuView];

     __weak typeof(self) weakSelf = self;
     BFActionBlock scroll = ^(BFScrollingDirection lastDirection) {
        NSLog(@"lastDirection = %ld", lastDirection);
        if (lastDirection == BFScrollingDirectionUP) {
            [UIView animateWithDuration:0.5 animations:^{
                weakSelf.menuView.frame = CGRectMake(0, 21, [UIScreen mainScreen].bounds.size.width, 0);
                //NSLog(@"animating hidden...");
            }];
        }
        else if (lastDirection == BFScrollingDirectionDown) {
            [UIView animateWithDuration:0.5 animations:^{
                weakSelf.menuView.frame = CGRectMake(0, 21, [UIScreen mainScreen].bounds.size.width, 80);
                //NSLog(@"animating showing...");
            }];
        }
    };

    [self setUpDelegateClass:[self class] MenuView:self.menuView conditionBlock:nil scrollActionBlock:scroll stopActionBlock:nil];
}

最終效果如下:

BFScrollMenu.gif

如果你喜歡,請幫忙在git上給一個star ~~ 謝謝!歡迎大家指正做commit!

2016.6.10 完稿于南京

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容