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

iOS 多視圖滑動點擊切換的封裝實作

編輯:iOS 開發綜合

前言

多視圖滑動點擊切換的效果在許多 App 中都很常見。本文示範如何將它封裝成一個元件,外界只需呼叫一個接口,就能達到類似系統 tabBarController 的使用體驗。

對外接口

/** 加入一個子控制器 */
- (void)addSubItemWithViewController:(UIViewController *)viewController;

效果預覽

HYTabbarView 可靈活設定一屏顯示幾個標題以及標題欄高度:

#define HYTabbarViewHeight 49   // 頂部標籤條的高度
#define HYColumn 4              // 一屏顯示 4 個標題

實作思路

1、介面分析:分為上下兩部分,頂部為 UIScrollView,底部為 UICollectionView(因底部視圖較複雜、佔用記憶體較大,用 CollectionView 會比 ScrollView 效能更好),再實作兩者的聯動即可。

2、每個標題對應一個 View,交由各自的控制器管理,讓不同 View 的業務邏輯高聚合、不產生耦合。

3、上下兩部分的聯動透過 KVO 實現:監聽 selectedIndex,底部滾動時修改該值,並在 KVO 回調中讓標題置中。

4、其他細節相對簡單,例如點擊頂部標題時設定按鈕選中並切換到對應的 CollectionCell。

UI 結構示意圖

程式碼片段

1. 加入一個欄目:

- (void)addSubItemWithViewController:(UIViewController *)viewController {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.tabbar addSubview:btn];
    [self setupBtn:btn withTitle:viewController.title];
    [btn addTarget:self action:@selector(itemSelected:) forControlEvents:UIControlEventTouchUpInside];
    [self.subViewControllers addObject:viewController];
}

2. 以 KVO 監聽當前選中 View 的序號:

// 於 viewDidLoad 中加入觀察者
[self addObserver:self forKeyPath:@"selectedIndex" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:@"scrollToNextItem"];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (context == @"scrollToNextItem") {
        self.prevSelectedIndex = [change[@"old"] integerValue];
        if (self.prevSelectedIndex == self.selectedIndex) {
            return;
        }
        [self itemSelectedIndex:self.selectedIndex];
        UIButton *btn = self.titles[self.selectedIndex];
        // 讓選中按鈕置中的計算邏輯……
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

使用方式:用法類似系統的 UITabbarController,外界只需直接傳入控制器:

- (HYTabbarView *)tabbarView {
    if (!_tabbarView) {
        _tabbarView = ({ HYTabbarView *tabbar = [[HYTabbarView alloc] initWithFrame:CGRectMake(0, 30, [UIScreen mainScreen].bounds.size.width, 600)];
            for (NSInteger i = 0; i < 10; i++) {
                UIViewController *vc = [[UIViewController alloc] init];
                vc.title = [NSString stringWithFormat:@"第%ld個", i + 1];
                [tabbar addSubItemWithViewController:vc];
            }
            tabbar;
        });
    }
    return _tabbarView;
}

小結

以上就是 iOS 多視圖滑動點擊切換的封裝實作,透過上下聯動與 KVO 監聽,即可提供流暢且易於整合的元件,希望對你的開發有所幫助。

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