您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

為 UITabBar 標籤切換加入靈巧的點擊動效

編輯:iOS 開發基礎

在 iOS 專案裡,為 UITabBarController 的標籤切換添加一點細膩的動畫,往往能讓整體操作手感更上一層樓。這篇文章就把這個做法完整拆解,附上可直接套用的程式碼,遇到疑問也歡迎一起交流。


先來看看實際效果。下面這個動畫來自筆者參與的專案,你可以依照自己的喜好微調參數,做成符合產品調性的樣子。

效果預覽

點擊下方的標籤時,圖示會有一個輕微的放大回弹效果。GIF 可能有點延遲、看起來不夠明顯,接著我們直接看程式碼。

核心程式碼

關鍵在於監聽標籤的選中事件,並在切換時觸發一段縮放動畫。透過 CABasicAnimation 對 transform.scale 做處理,就能達到「按下時放大再縮回」的視覺回饋。

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    NSInteger index = [self.tabBar.items indexOfObject:item];
    if (self.indexFlag != index) {
        [self animationWithIndex:index];
    }
}

// 縮放動畫
- (void)animationWithIndex:(NSInteger)index {
    NSMutableArray *tabbarbuttonArray = [NSMutableArray array];
    for (UIView *tabBarButton in self.tabBar.subviews) {
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [tabbarbuttonArray addObject:tabBarButton];
        }
    }
    CABasicAnimation *pulse = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    pulse.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pulse.duration = 0.08;
    pulse.repeatCount = 1;
    pulse.autoreverses = YES;
    pulse.fromValue = [NSNumber numberWithFloat:0.7];
    pulse.toValue = [NSNumber numberWithFloat:1.3];
    [[tabbarbuttonArray[index] layer] addAnimation:pulse forKey:nil];
    self.indexFlag = index;
}

這裡用 indexFlag 記錄目前選中的標籤,避免重複點擊同一項時又觸發一次動畫。透過 autoreverses = YES 搭配 fromValue 與 toValue,動畫就會自然地放大再縮回,營造出活潑但不浮誇的感覺。

文章轉自 MrBrave丶彬彬的簡書

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved