在實作專案時,我遇到一個惱人的問題:TableView 本身實作了 sectionIndexTitlesForTableView: 方法,右側會出現字母檢索列,但最後幾個位置(例如「#」)無論怎麼點擊,都無法準確把對應的列表項滾動顯示出來。
於是我在 tableView:sectionForSectionIndexTitle:atIndex: 方法中重寫了定位邏輯,透過自訂的滾動方式來修正這個問題。程式碼如下:
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
// 1. 取得目前 index 對應 section 的原始 y
// 2. 用 contentSize.height 減去 y,得到 lefty
// 3. 若 lefty 大於等於可視高度,就滾動到 y
// 4. 否則滾動到最底部
CGFloat y = [self getYOffSet:index title:title];
if (tableView.contentSize.height - y >= tableView.frame.size.height) {
[tableView setContentOffset:CGPointMake(0, y) animated:NO];
} else {
[tableView setContentOffset:CGPointMake(0, tableView.contentSize.height - tableView.frame.size.height) animated:NO];
}
return NSNotFound;
}
接著實作計算偏移量的輔助方法:
-(float)getYOffSet:(NSInteger)index title:(NSString *)title {
// offY = 100 是因為我在最上面加了兩個 section 顯示別的內容,
// 不在此計算範圍內;若不需要特別提示,可設為 0
float offY = 100;
int count = 0;
// 對應的所有內容高度
float addOffy = 0;
// 統計有內容的標題數量,用來計算占用的 header 高度
// 例:a 標題下有 aaa、abc、abcd,則 a 不為空,addTitleCount 加 1
float addTitleCount = 0;
// sectionTitles 是 a-z 加上 # 的列表
// dataSource 記錄每個 section 中有幾項內容
for (NSString *string in self.sectionTitles) {
if ([string isEqualToString:title]) {
break;
}
addOffy += 50 * [[self.dataSource objectAtIndex:count] count];
if ([[self.dataSource objectAtIndex:count] count] != 0) {
addTitleCount++;
}
count++;
}
// 22 是 viewForHeader 的高度
return offY + 22 * addTitleCount + addOffy;
}
這裡的關鍵思路是:手動累加「目標索引之前」所有 section 的內容高度與 header 高度,算出真正的 y 偏移,再自行呼叫 setContentOffset 滾動。這樣一來,即使是索引列最尾端的「#」或空 section,也能被準確定位。實務上,這比單純依賴系統預設的 section 換算更可靠,特別適合內容動態、section 有空的清單。