業(yè)務(wù)需求:在選中某一Tab后,為其添加單擊和雙擊事件(注意單擊雙擊事件必須需獨(dú)立,不能同時(shí)觸發(fā))
方案構(gòu)思:
方案一:利用圖層分析工具和KVC在
UITabBarItem上添加自定義View,然后在View分別添加單擊和雙擊手勢(shì)
因?yàn)锳pp原本使用的UITabBar,而UITabBarItem繼承NSObject,因此必須通過(guò)圖層分析工具獲取UITabBarItem里面的UI對(duì)象的類名,然后用runtime和KVC添加或修改屬性。但稍加思考后,放棄了這種方案,原因有二:第一、可能用到蘋果私有API,審核被拒。第二、每一個(gè)版本的UITabBarItem的UI對(duì)象都可能有所改變,至少在iOS8,13,15這幾個(gè)版本UITabBarItem的UI圖層都略有改變。這樣一來(lái)封裝的代碼非常麻煩,而且對(duì)于未來(lái)也iOS系統(tǒng)版本也有變數(shù)。方案二:直接在
UITabBar上添加視圖
這種方案的確比方案一穩(wěn)定,但從代碼封裝角度來(lái)說(shuō),非常丑陋。方案三:在
UITabBarControllerDelegate的- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController中添加通知事件,利用觸發(fā)的時(shí)間間隔來(lái)區(qū)分單擊和雙擊事件
通過(guò)研究發(fā)現(xiàn),不論是在視圖上添加手勢(shì)還是利用時(shí)間間隔觸發(fā)通知都有一個(gè)問(wèn)題,就是雙擊事件事件沒(méi)法脫離單擊獨(dú)立出現(xiàn)(因?yàn)榈谝淮吸c(diǎn)擊你是沒(méi)法區(qū)分單雙擊的)
這里涉及一個(gè)技巧,就是單擊事件需要延遲執(zhí)行,如果雙擊事件觸發(fā)了,則將處于延遲等待的單擊事件取消掉。代碼如下
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
///第二個(gè)item是你要處理單雙擊的情況
///tapTimestamp用于記錄上一次點(diǎn)擊的時(shí)間戳。
///doubleTapInterval是一個(gè)靜態(tài)常量(我設(shè)置的為0.3)
NSUInteger index = [tabBarController.viewControllers indexOfObject:viewController];
if (index == 1 && tabBarController.selectedIndex == 1) {
NSTimeInterval timestamp = CFAbsoluteTimeGetCurrent();
if (timestamp - self.tapTimestamp < doubleTapInterval) {
[self postDoubleTapNotification];
}else {
[self performSelector:@selector(postSingleTapNotification) afterDelay:doubleTapInterval];
}
self.tapTimestamp = timestamp;
return NO;
}
return YES;
}
- (void)postSingleTapNotification {
[NotiCenter postNotificationName:LSTabBarSingleTapNotification object:nil];
}
- (void)postDoubleTapNotification {
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(postSingleTapNotification) object:nil];
[NotiCenter postNotificationName:LSTabBarDoubleTapNotification object:nil];
}