Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義實現:點擊狀態欄快速回到頂部

編輯:關於 Android 程式設計

點擊屏幕最上方的狀態欄(status)時,如果當前是TableView或可滾動的控件,就讓它平滑滾動到最頂部的位置

#import "LZPStatuesClickWindow.h" //定義一個全局變量,整個程序的 lifecycle 都存在 UIWindow * _statueWindow; @interface LZPStatuesClickWindow () @end @implementation LZPStatuesClickWindow +(void)show{ //需要在info.plist中設置status的管理(不讓系統管理status); //1.自定義window的級別要高 //2.自定義window需要強引用 //3.如果點擊一個類,沒有調用該類的方法,則看一下這個對象是什麼類型(如果對象和方法的類不是同一個類,就不會調用); UIApplication * application = [UIApplication sharedApplication]; //注意:這裡創建的是繼承自UIWindow的類,因此在外部調用該方法時是該類自身調用,要用self,而不是用window創建(用window創建在被點擊時不會響應該類中的touch方法); UIWindow * statueWindow = [[self alloc] initWithFrame:application.statusBarFrame]; //設置級別,不設置會顯示在下方被主窗口蓋住 statueWindow.windowLevel = UIWindowLevelAlert; //窗口需要設置根控制器 statueWindow.rootViewController = [[UIViewController alloc] init]; //當有多個窗口顯示時,非主窗口會隱藏,這裡設置顯示 statueWindow.hidden = NO; //設置窗口屬性,下面會用到 _statueWindow = statueWindow; } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ UIWindow * keyWidow = [UIApplication sharedApplication].keyWindow; [self setViewController:keyWidow]; } //該方法遞歸遍歷主窗口下所有的子控件,直到找出我們想要的 //使用遞歸,一層一層地遍歷 -(void)setViewController:(UIView *)view{ for (UIView * childView in view.subviews) { if ([childView isKindOfClass:[UITableView class]]) { //強制轉換一下,才能拿到tableview的屬性 UITableView * tableView = (UITableView *)childView; [tableView setContentOffset:CGPointMake(0, -tableView.contentInset.top) animated:YES]; } [self setViewController:childView]; } }

在AppDelegate中調用:

application.statusBarHidden = NO;

一定要將系統的狀態欄顯示出來,因為當有多個窗口時系統狀態欄會隱藏(默認是顯示的)

 [LZPStatuesClickWindow show]; 
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved