how can i make headerView scroll (not stay on the

2020-06-08 07:18发布

in plainsytle tableview , we set headerViews for each section by delegate method

-(UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section 

so,when i scrolling up tableview , the first section's headerView is always showing on the top of tableview before the section totally disappear on the tableview , then the second section's headerView will show on the top of tableview instead . so my question is how can i make headerView scroll accompanying with uitableViewCell , just like group style tableview ?

8条回答
▲ chillily
2楼-- · 2020-06-08 07:54

Swift:

As Hani Ibrahim pointed out you need to subclass UITableView. Apple says you : must specify style at creation.

So:

override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: .grouped)

Notice how my super.init uses .grouped as the style. For this style of tableview (.grouped) Apple also says:

Summary

A table view whose sections present distinct groups of rows. The section headers and footers do not float.

Then you can call the following tableView delegate methods: viewForHeaderInSection and heightForHeaderInSection (notice those are for headers only, use the footer counterparts if you want footers too)

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerLabel = UILabel()
        headerLabel.text = "My cool header title"
        headerLabel.textAlignment = .center
        headerLabel.font = UIFont(name: "OpenSans-Bold", size: 16)
        return headerLabel
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }

And that should do it! Good luck.

查看更多
成全新的幸福
3楼-- · 2020-06-08 07:55

You can change the style of the tableView.

let tableView = UITableView(frame: .zero, style: .grouped)
查看更多
登录 后发表回答