抖音首頁的頭部滑動標簽(通常稱為"Segmented Control"或"Tab Bar")是一個常見的UI組件,可以通過以下幾種方式實現:
1. 使用UISegmentedControl
最簡單的實現方式是使用系統自帶的UISegmentedControl
:
let segmentedControl = UISegmentedControl(items: ["推薦", "關注", "同城"])
segmentedControl.selectedSegmentIndex = 0
segmentedControl.addTarget(self, action: #selector(segmentChanged(_:)), for: .valueChanged)
navigationItem.titleView = segmentedControl @objc func segmentChanged(_ sender: UISegmentedControl) {// 處理標簽切換 print("Selected segment: \(sender.selectedSegmentIndex)")
}
2. 自定義實現(更接近抖音效果)
抖音的效果通常是水平滾動的標簽欄,可以這樣實現:
import UIKit class TikTokTabBar: UIView {private let scrollView = UIScrollView()private var buttons: [UIButton] = []private let indicator = UIView()private var currentIndex: Int = 0 var titles: [String] = [] {didSet {setupButtons()}}var onTabSelected: ((Int) -> Void)?override init(frame: CGRect) {super.init(frame: frame)setupUI()}required init?(coder: NSCoder) {super.init(coder: coder)setupUI()}private func setupUI() {scrollView.showsHorizontalScrollIndicator = false addSubview(scrollView)indicator.backgroundColor = .red scrollView.addSubview(indicator)}override func layoutSubviews() {super.layoutSubviews()scrollView.frame = bounds var x: CGFloat = 0 let buttonHeight = bounds.height - 4 let padding: CGFloat = 20 for (index, button) in buttons.enumerated() {let width = button.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: buttonHeight)).width + padding * 2 button.frame = CGRect(x: x, y: 0, width: width, height: buttonHeight)x += width if index == currentIndex {indicator.frame = CGRect(x: button.frame.minX + padding, y: buttonHeight, width: button.frame.width - padding * 2, height: 3)}}scrollView.contentSize = CGSize(width: x, height: bounds.height)}private func setupButtons() {buttons.forEach { $0.removeFromSuperview() }buttons.removeAll()for (index, title) in titles.enumerated() {let button = UIButton(type: .custom)button.setTitle(title, for: .normal)button.setTitleColor(index == 0 ? .white : .lightGray, for: .normal)button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)button.tag = index scrollView.addSubview(button)buttons.append(button)}}@objc private func buttonTapped(_ sender: UIButton) {selectTab(at: sender.tag, animated: true)onTabSelected?(sender.tag)}func selectTab(at index: Int, animated: Bool) {guard index >= 0 && index < buttons.count else { return }let button = buttons[index]currentIndex = index UIView.animate(withDuration: animated ? 0.25 : 0) {self.buttons.forEach {$0.setTitleColor($0.tag == index ? .white : .lightGray, for: .normal)}self.indicator.frame = CGRect(x: button.frame.minX + 20, y: button.frame.height, width: button.frame.width - 40, height: 3)// 確保選中的標簽可見 let visibleRect = CGRect(x: button.frame.minX - 30, y: 0, width: button.frame.width + 60, height: self.scrollView.frame.height)self.scrollView.scrollRectToVisible(visibleRect, animated: animated)}}
}
3. 結合PageViewController實現完整效果
要實現抖音首頁的完整效果(滑動標簽同時控制頁面切換),可以結合UIPageViewController
:
class TikTokHomeViewController: UIViewController {private let tabBar = TikTokTabBar()private var pageViewController: UIPageViewController!private var viewControllers: [UIViewController] = []override func viewDidLoad() {super.viewDidLoad()// 設置標簽欄 tabBar.titles = ["推薦", "關注", "同城"]tabBar.onTabSelected = { [weak self] index in self?.selectPage(at: index, animated: true)}navigationItem.titleView = tabBar // 設置頁面控制器 pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)pageViewController.delegate = self pageViewController.dataSource = self // 添加子控制器 viewControllers = [RecommendationViewController(),FollowingViewController(),NearbyViewController()]addChild(pageViewController)view.addSubview(pageViewController.view)pageViewController.didMove(toParent: self)pageViewController.setViewControllers([viewControllers[0]], direction: .forward, animated: false)}private func selectPage(at index: Int, animated: Bool) {guard index >= 0 && index < viewControllers.count else { return }let direction: UIPageViewController.NavigationDirection = index > tabBar.currentIndex ? .forward : .reverse pageViewController.setViewControllers([viewControllers[index]], direction: direction, animated: animated)tabBar.selectTab(at: index, animated: animated)}
}extension TikTokHomeViewController: UIPageViewControllerDelegate, UIPageViewControllerDataSource {func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {guard let index = viewControllers.firstIndex(of: viewController), index > 0 else { return nil }return viewControllers[index - 1]}func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {guard let index = viewControllers.firstIndex(of: viewController), index < viewControllers.count - 1 else { return nil }return viewControllers[index + 1]}func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {if completed, let currentVC = pageViewController.viewControllers?.first, let index = viewControllers.firstIndex(of: currentVC) {tabBar.selectTab(at: index, animated: true)}}
}
高級優化
1. 動畫效果:可以添加更流暢的滑動動畫和指示器動畫
2. 字體縮放:選中的標簽可以放大字體,未選中的縮小
3. 預加載:預加載相鄰的頁面以提高響應速度
4. 性能優化:對于大量標簽,實現重用機制
下面是優化的具體實現
1. 平滑滑動動畫與指示器效果優化
實現思路
- 監聽UIScrollView的滾動偏移量
- 根據偏移量動態計算指示器位置和寬度
- 實現標簽顏色漸變效果
代碼實現
// 在TikTokTabBar類中添加以下方法
private var lastContentOffset: CGFloat = 0 func scrollViewDidScroll(_ scrollView: UIScrollView) {guard scrollView.isTracking || scrollView.isDragging || scrollView.isDecelerating else { return }let offsetX = scrollView.contentOffset.x let scrollViewWidth = scrollView.bounds.width let progress = (offsetX / scrollViewWidth) - CGFloat(currentIndex)// 防止快速滑動時progress超出范圍 let clampedProgress = max(-1, min(1, progress))updateTabAppearance(progress: clampedProgress)updateIndicatorPosition(progress: clampedProgress)lastContentOffset = offsetX
}private func updateTabAppearance(progress: CGFloat) {let absProgress = abs(progress)for (index, button) in buttons.enumerated() {// 當前標簽和下一個標簽 if index == currentIndex || index == currentIndex + (progress > 0 ? 1 : -1) {let isCurrent = index == currentIndex let targetIndex = isCurrent ? (progress > 0 ? currentIndex + 1 : currentIndex - 1) : currentIndex guard targetIndex >= 0 && targetIndex < buttons.count else { continue }let targetButton = buttons[targetIndex]// 顏色漸變 let currentColor = UIColor.white let targetColor = UIColor.lightGray let color = isCurrent ? currentColor.interpolate(to: targetColor, progress: absProgress) : targetColor.interpolate(to: currentColor, progress: absProgress)button.setTitleColor(color, for: .normal)// 字體縮放 let minScale: CGFloat = 0.9 let maxScale: CGFloat = 1.1 let scale = isCurrent ? maxScale - (maxScale - minScale) * absProgress : minScale + (maxScale - minScale) * absProgress button.transform = CGAffineTransform(scaleX: scale, y: scale)} else {// 其他標簽保持默認狀態 button.setTitleColor(.lightGray, for: .normal)button.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)}}
}private func updateIndicatorPosition(progress: CGFloat) {guard currentIndex >= 0 && currentIndex < buttons.count else { return }let currentButton = buttons[currentIndex]var nextIndex = currentIndex + (progress > 0 ? 1 : -1)nextIndex = max(0, min(buttons.count - 1, nextIndex))let nextButton = buttons[nextIndex]let absProgress = abs(progress)// 計算指示器位置和寬度 let currentFrame = currentButton.frame let nextFrame = nextButton.frame let originX = currentFrame.minX + (nextFrame.minX - currentFrame.minX) * absProgress let width = currentFrame.width + (nextFrame.width - currentFrame.width) * absProgress indicator.frame = CGRect(x: originX + 20,y: currentFrame.height,width: width - 40,height: 3 )
}// UIColor擴展,用于顏色插值
extension UIColor {func interpolate(to color: UIColor, progress: CGFloat) -> UIColor {var fromRed: CGFloat = 0, fromGreen: CGFloat = 0, fromBlue: CGFloat = 0, fromAlpha: CGFloat = 0 var toRed: CGFloat = 0, toGreen: CGFloat = 0, toBlue: CGFloat = 0, toAlpha: CGFloat = 0 self.getRed(&fromRed, green: &fromGreen, blue: &fromBlue, alpha: &fromAlpha)color.getRed(&toRed, green: &toGreen, blue: &toBlue, alpha: &toAlpha)let red = fromRed + (toRed - fromRed) * progress let green = fromGreen + (toGreen - fromGreen) * progress let blue = fromBlue + (toBlue - fromBlue) * progress let alpha = fromAlpha + (toAlpha - fromAlpha) * progress return UIColor(red: red, green: green, blue: blue, alpha: alpha)}
}
2. 字體縮放效果優化
實現思路
- 根據滑動進度動態調整標簽字體大小
- 當前選中標簽放大,相鄰標簽適當縮小
- 其他標簽保持最小尺寸
代碼實現
上面的updateTabAppearance
方法已經包含了字體縮放邏輯,這里補充字體縮放的具體參數:
// 在updateTabAppearance方法中添加以下參數
let minScale: CGFloat = 0.9 // 最小縮放比例
let maxScale: CGFloat = 1.1 // 最大縮放比例
let scale = isCurrent ? maxScale - (maxScale - minScale) * absProgress : minScale + (maxScale - minScale) * absProgress button.transform = CGAffineTransform(scaleX: scale, y: scale)
3. 頁面預加載機制
實現思路
- 預加載當前頁面相鄰的頁面
- 使用UIPageViewController的緩存機制
- 監聽滑動方向提前準備內容
代碼實現
// 在TikTokHomeViewController中添加預加載邏輯
private var pendingIndex: Int?
private var direction: UIPageViewController.NavigationDirection = .forward func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {if let pendingVC = pendingViewControllers.first,let index = viewControllers.firstIndex(of: pendingVC) {pendingIndex = index }
}func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {if completed, let pendingIndex = pendingIndex {currentIndex = pendingIndex tabBar.selectTab(at: currentIndex, animated: true)// 預加載相鄰頁面 preloadAdjacentPages()}pendingIndex = nil
}private func preloadAdjacentPages() {// 預加載前一個頁面 if currentIndex > 0 {let previousIndex = currentIndex - 1 if let previousVC = pageViewController.dataSource?.pageViewController(pageViewController,viewControllerBefore: viewControllers[currentIndex]) {// 確保視圖已加載 _ = previousVC.view }}// 預加載后一個頁面 if currentIndex < viewControllers.count - 1 {let nextIndex = currentIndex + 1 if let nextVC = pageViewController.dataSource?.pageViewController(pageViewController,viewControllerAfter: viewControllers[currentIndex]) {// 確保視圖已加載 _ = nextVC.view }}
}// 修改selectPage方法以支持方向判斷
private func selectPage(at index: Int, animated: Bool) {guard index >= 0 && index < viewControllers.count else { return }direction = index > currentIndex ? .forward : .reverse pageViewController.setViewControllers([viewControllers[index]], direction: direction, animated: animated) { [weak self] _ in self?.preloadAdjacentPages()}currentIndex = index tabBar.selectTab(at: index, animated: animated)
}
4. 性能優化與標簽重用
實現思路
- 對于大量標簽,實現重用機制
- 只保留可視區域附近的標簽
- 動態加載和卸載標簽
代碼實現
// 在TikTokTabBar中添加重用邏輯
private let reusableQueue = NSMutableSet()
private var visibleButtons =
private var allTitles = func setTitles(_ titles: [String]) {allTitles = titles updateVisibleButtons()
}private func updateVisibleButtons() {// 計算當前可見范圍 let visibleRange = calculateVisibleRange()// 移除不再可見的按鈕 for (index, button) in visibleButtons {if !visibleRange.contains(index) {button.removeFromSuperview()reusableQueue.add(button)visibleButtons.removeValue(forKey: index)}}// 添加新可見的按鈕 for index in visibleRange {if visibleButtons[index] == nil {let button = dequeueReusableButton()configureButton(button, at: index)scrollView.addSubview(button)visibleButtons[index] = button }}// 更新布局 setNeedsLayout()
}private func calculateVisibleRange() -> ClosedRange<Int> {let contentOffsetX = scrollView.contentOffset.x let visibleWidth = scrollView.bounds.width // 計算第一個和最后一個可見的索引 var startIndex = 0 var endIndex = allTitles.count - 1 // 這里可以添加更精確的計算邏輯 // 例如根據按鈕寬度和偏移量計算 // 擴展可見范圍,預加載左右各2個 startIndex = max(0, startIndex - 2)endIndex = min(allTitles.count - 1, endIndex + 2)return startIndex...endIndex
}private func dequeueReusableButton() -> UIButton {if let button = reusableQueue.anyObject() as? UIButton {reusableQueue.remove(button)return button }return UIButton(type: .custom)
}private func configureButton(_ button: UIButton, at index: Int) {button.setTitle(allTitles[index], for: .normal)button.setTitleColor(index == currentIndex ? .white : .lightGray, for: .normal)button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)button.tag = index
}// 在scrollViewDidScroll中調用updateVisibleButtons
func scrollViewDidScroll(_ scrollView: UIScrollView) {updateVisibleButtons()// 其他滾動邏輯...
}
5. 綜合優化與細節處理
5.1 彈性效果限制
// 在TikTokTabBar中
scrollView.bounces = false
scrollView.alwaysBounceHorizontal = false
5.2 點擊動畫效果
@objc private func buttonTapped(_ sender: UIButton) {// 點擊動畫 UIView.animate(withDuration: 0.1, animations: {sender.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)}) { _ in UIView.animate(withDuration: 0.1) {sender.transform = .identity }}selectTab(at: sender.tag, animated: true)onTabSelected?(sender.tag)
}
5.3 性能優化提示
// 在TikTokTabBar的初始化中
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
5.4 內存管理優化
// 在視圖控制器中
deinit {scrollView.delegate = nil
}
總結
通過以上高級優化實現,你可以獲得一個接近抖音效果的滑動標簽欄,具有以下特點:
- 平滑的滑動動畫和指示器過渡效果
- 動態字體縮放和顏色漸變
- 高效的頁面預加載機制
- 優化的性能與內存管理
- 標簽重用機制支持大量標簽
這些優化可以顯著提升用戶體驗,使滑動更加流暢,響應更加迅速,同時保持良好的內存使用效率。