「頂部一排標籤、可左右滑動、點一下切換內容」是極常見的互動模式。與其每個頁面各寫一次,不如把它封裝成一個元件,外部只需呼叫一個 API 把子控制器塞進去。
開源實作可參考:https://github.com/HelloYeah/HYTabbarView
// 加入一個子控制器
- (void)addSubItemWithViewController:(UIViewController *)viewController;
- (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];
}
值得注意的是標題直接取自 viewController.title,這樣呼叫端不必額外傳字串,設定一次就能保持一致。
真正的細節在這裡。使用者點擊某個標籤後,選單列應該要把該項目滾到中央;同時在抵達頭尾時要停止,避免出現空白:
NSInteger min = HYColumn / 2;
if (_selectedIndex == self.titles.count - min) {
// 已接近尾端:只捲到最後一個可顯示的位置
UIButton *tempBtn = self.titles[self.titles.count - min - 1];
CGFloat btnX = (HYColumn % 2) ? tempBtn.center.x
: (tempBtn.center.x + btn.frame.size.width * 0.5);
CGFloat offsetX = _tabbar.center.x - btnX;
[UIView animateWithDuration:0.25 animations:^{
_tabbar.contentOffset = CGPointMake(-offsetX, 0);
}];
} else if (_selectedIndex > min && _selectedIndex < self.titles.count - min
&& self.titles.count > HYColumn) {
// 中段:把選中項置中
CGFloat btnX = (HYColumn % 2) ? btn.center.x
: (btn.center.x - btn.frame.size.width * 0.5);
CGFloat offsetX = _tabbar.center.x - btnX;
[UIView animateWithDuration:0.25 animations:^{
_tabbar.contentOffset = CGPointMake(-offsetX, 0);
}];
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
這段邏輯跑在 KVO 的回呼裡,因此 keyPath 必須先比對確認是我們關注的那個屬性,否則會攔截到無關的變更通知——範例中最後的 else 分支就是為了把其他 keyPath 交回父類處理。
另外,HYColumn 是一列可顯示的項目數,二分之後得到「置中所需的緩衝」。HYColumn % 2 的判斷則是在處理奇偶數欄位時,中心點該落在按鈕的 center 還是邊緣,這一步很容易在改成不同欄數後出錯,調整版面時務必一併檢查。
最後,若你的專案已全面採用 Auto Layout,改用 UICollectionView 搭配 UICollectionViewFlowLayout 並指定水平捲動,可以省下大量手動計算 contentOffset 的工作,scrollToItemAtIndexPath:atScrollPosition:animated: 一行就能完成置中。