現(xiàn)在很多App重復(fù)點(diǎn)擊TabBarItem都可以刷新當(dāng)前界面税弃,可以通過通知的方式來監(jiān)聽TabBarItem的點(diǎn)擊
1.來到AppDelegate中發(fā)出通知,先遵守<UITabBarControllerDelegate>
@interface AppDelegate ()<UITabBarControllerDelegate>
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
//創(chuàng)建一個(gè)帶導(dǎo)航的根控制器
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[[ViewController alloc] init]];
UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:[[OtherViewController alloc] init]];
UITabBarController *tabBarController = [[UITabBarController alloc] init];
tabBarController.viewControllers = @[nav,nav1];
nav.tabBarItem.title = @"消息";
nav1.tabBarItem.title = @"發(fā)現(xiàn)";
self.window.rootViewController = tabBarController;
tabBarController.delegate = self;
return YES;
}
//UITabBarController代理方法
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
static NSString *tabBarDidSelectedNotification = @"tabBarDidSelectedNotification";
//當(dāng)tabBar被點(diǎn)擊時(shí)發(fā)出一個(gè)通知
[[NSNotificationCenter defaultCenter] postNotificationName:tabBarDidSelectedNotification object:nil userInfo:nil];
}
2.來到需要監(jiān)聽TabBarItem的選中的控制器
@interface ViewController ()
/** 上次選中的索引(或者控制器) */
@property (nonatomic, assign) NSInteger lastSelectedIndex;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
static NSString *tabBarDidSelectedNotification = @"tabBarDidSelectedNotification";
//注冊(cè)接收通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabBarSeleted) name:tabBarDidSelectedNotification object:nil];
}
// 接收到通知實(shí)現(xiàn)方法
- (void)tabBarSeleted {
// 如果是連續(xù)選中2次, 直接刷新
if (self.lastSelectedIndex == self.tabBarController.selectedIndex && [self isShowingOnKeyWindow]) {
//直接寫刷新代碼
}
// 記錄這一次選中的索引
self.lastSelectedIndex = self.tabBarController.selectedIndex;
}
/**
* 判斷一個(gè)控件是否真正顯示在主窗口
*/
- (BOOL)isShowingOnKeyWindow
{
// 主窗口
UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
// 以主窗口左上角為坐標(biāo)原點(diǎn), 計(jì)算self的矩形框
CGRect newFrame = [keyWindow convertRect:self.view.frame fromView:self.view.superview];
CGRect winBounds = keyWindow.bounds;
// 主窗口的bounds 和 self的矩形框 是否有重疊
BOOL intersects = CGRectIntersectsRect(newFrame, winBounds);
return !self.view.isHidden && self.view.alpha > 0.01 && self.view.window == keyWindow && intersects;
}
類似網(wǎng)易新聞首頁毁欣,不同的控制器View添加到一個(gè)ScrollView上庇谆,這個(gè)時(shí)候就需要判斷手機(jī)顯示的是哪個(gè)控制器View,就需要用到上面<判斷一個(gè)控件是否真正顯示在主窗口>的這個(gè)方法凭疮,如果沒有這個(gè)判斷饭耳,點(diǎn)擊兩次Item,所有添加到ScrollView上的控制器View都會(huì)刷新哭尝。