tableview: 實現tableview 的 section header 跟隨tableview滑動


   方法一:(只有一個headerView)一段

        如果你的tableview恰好只有一個headerView,實現這種效果就好辦了。把要設置的headerView設置成tableView的header而不是section = 0的headerView。

self.tableView.tableHeaderView = view;

    方法二:

        該方法比較簡單,設置tableView的style為UITableViewStyleGrouped即可。代碼如下

        self.tableView = [[UITableView alloc]initWithFrame:[[UIScreen mainScreen]bounds] style:UITableViewStyleGrouped];  

        當設置成grouped類型之后,頭部會出現空白,在每一個section之間也會出現空白,解決方法如下(swift代碼):

        設置tableHeaderView的高度為一個比較小的值。

         let view = UIView.init(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height:0.001))
         self.tableView.tableHeaderView = view

 

         設置每一段的段尾值為一個比較小的值,去除空白。

          func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
                   return 0.01
          }

    方法三:

        由於tableView是特殊的scrollView,在controller中加入如下代碼:

 

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

        CGFloat sectionHeaderHeight = self.sectionHeight;       

        // NSLog(@"%f,%f",scrollView.contentOffset.x,scrollView.contentOffset.y);   

        if(scrollView == self.tableView){       

          if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>= -64) {  

                    scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);       

          } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {         

               scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);       

          }   

        }   

       }  

        

        其中sectionHeight為你的tableview的section=0的headerView的高度。

        由於我的tableViewController是在navigationController中使用的,而使用navigationController會使tableView(scrollView)的subView整體下移64,所以使用scrollView.contentOffset.y>=-64,如果沒有使用navigationController就應該使用scrollView.contentOffset.y>=-64。這個根據自己的情況設置就好了。


免責聲明!

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



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