iOS UITableView獲取特定位置的cell


代碼地址如下:
http://www.demodashi.com/demo/13307.html

一、tableView雙級聯動

菜單欄聯動.gif

UITableView雙級聯動.gif

以上兩種效果比較類似,實現的關鍵在於都是需要獲得在滑動過程中滑動到tableView頂部的cell的indexPath。

方案一:獲得當前可見的所有cell,然后取可見cell數組中的第一個cell就是目標cell,再根據cell獲得indexPath。代碼如下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
  if (scrollView == _rightTableView && _isSelected == NO) {
      //返回tableView可見的cell數組
        NSArray * array = [_rightTableView visibleCells];
       //返回cell的IndexPath
        NSIndexPath * indexPath = [_rightTableView indexPathForCell:array.firstObject];
        NSLog(@"滑到了第 %ld 組 %ld個",indexPath.section, indexPath.row);
        _currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
        [_leftTableView reloadData];
        [_leftTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.section] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
    }
    
}

方案二(推薦使用):利用偏移量!偏移量的值實際上可以代表當時處於tableView頂部的cell在tableView上的相對位置, 那么我們就可以根據偏移量獲得處於頂部的cell的indexPath。代碼如下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
   if (scrollView == _rightTableView && _isSelected == NO) {
       //系統方法返回處於tableView某坐標處的cell的indexPath
        NSIndexPath * indexPath = [_rightTableView indexPathForRowAtPoint:scrollView.contentOffset];
        NSLog(@"滑到了第 %ld 組 %ld個",indexPath.section, indexPath.row);
        _currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
        [_leftTableView reloadData];
        [_leftTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.section] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
    }
    
}

二、 獲取處於UITableView中心的cell

獲取UITableView中心線cell.gif

獲取處於tableView中間cell的效果,用上述方案一比較麻煩:要考慮可見cell 的奇、偶個數問題,還有cell是否等高的情況;方案二用起來就快捷方便多了,取的cell的位置的縱坐標相當於在偏移量的基礎上又增加了tableView高度的一半。代碼如下:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    //獲取處於UITableView中心的cell
    //系統方法返回處於tableView某坐標處的cell的indexPath
    NSIndexPath * middleIndexPath = [_rightTableView  indexPathForRowAtPoint:CGPointMake(0, scrollView.contentOffset.y + _rightTableView.frame.size.height/2)];
    NSLog(@"中間的cell:第 %ld 組 %ld個",middleIndexPath.section, middleIndexPath.row);

}

三、項目結構

俺目前能想到的也就這了,各位同僚有什么好的想法歡迎在此留言交流😀😁😀👏👏👏

iOS UITableView獲取特定位置的cell

代碼地址如下:
http://www.demodashi.com/demo/13307.html

注:本文著作權歸作者,由demo大師代發,拒絕轉載,轉載需要作者授權


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM