Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

前端 未结 29 1094
走了就别回头了
走了就别回头了 2020-11-29 15:02

I\'m using a UITableView to layout content \'pages\'. I\'m using the headers of the table view to layout certain images etc. and I\'d prefer it if they didn\'t

29条回答
  •  孤城傲影
    2020-11-29 15:27

    There is another tricky way. The main idea is to double the section number, and first one only shows the headerView while the second one shows the real cells.

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return sectionCount * 2;
    }
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        if (section%2 == 0) {
            return 0;
        }
        return _rowCount;
    }
    

    What need to do then is to implement the headerInSection delegates:

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
        if (section%2 == 0) {
            //return headerview;
        }
        return nil;
    }
    
    - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
        if (section%2 == 0) {
            //return headerheight;
        }
        return 0;
    }
    

    This approach also has little impact on your datasources:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        int real_section = (int)indexPath.section / 2;
        //your code
    }
    

    Comparing with other approaches, this way is safe while not changing the frame or contentInsets of the tableview. Hope this may help.

提交回复
热议问题