1. 程式人生 > >iOS UITableView 快速滾動(索引方式實現)

iOS UITableView 快速滾動(索引方式實現)

參考:http://my.oschina.net/joanfen/blog/204503

思路:UITableView一次性載入資料過多時,需要滑動多次觸底。想通過索引實現快速滑動,索引中載入20個空點。使用者在最右端滑動時,索引框顯示,當觸及索引點時指向其想對應的UITableView的RowIndex來實現快速滾動。這方法有缺陷:普通滑動時滾動條被遮蓋了。

主要程式碼:

//獲取資料
-(void)getTableData{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            // 獲取資料庫資料
            self.listArray = [[ReportLogic sharedInstance] getProductByCategory];
            if ([self.listArray count] == 0) {
                [GlobalApplication Alert:@"提示" :@"暫無資料"];
            }else{
                // 索引目錄,20個空點
                NSMutableArray *stArray =  [[NSMutableArray alloc] init];
                self.sectionTitles = stArray;
                [stArray release];
                for (int i=0;i<20;i++)
                {
                    NSString *index = @"";
                    [self.sectionTitles insertObject:index atIndex:i];
                }
            }
            // 資料重新整理
            [self.fmTableView reloadData];
        });
    });
}

#pragma mark index
// 分割槽數
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{  
    return 1;
}

// 索引目錄
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{

    return self.sectionTitles;
}

// 滑動時點選目錄
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    
     // 修正索引焦點為UITableView的RowIndex,頭尾和中間值
    if (index == 0) {
        index = 1;
    }else if(index == self.sectionTitles.count - 1){
        index = self.listArray.count -1;
    }else
         index = round(index*self.listArray.count/20);
    [self.fmTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    return index;
}
 

效果: