I found the solution is to remove the content from the tableview section header while the section header is sticky to the top. Add it to the view instead.
Then we can refresh the section or the tableview. If we scroll down then, put the header back to the section header container.
to remove the section header, when a button inside the header
@objc func refreshSection(){
if sectionHeaderStickyTop == true {
guard let header = sectionHeaderContainer.subviews.first else {
return
}
sectionHeaderStickyTop = false
header.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(header)
let guide = view.safeAreaLayoutGuide
header.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
header.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
header.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
header.heightAnchor.constraint(equalToConstant: header.bounds.size.height).isActive = true
}
table.reloadSections(IndexSet(integer: 0), with: UITableView.RowAnimation.none)
}
put the header back to the section header, if the header has been
removed
func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard let tableView = scrollView as? UITableView else {
return
}
let header = sectionHeader
dummyButton.setTitle("\(Int.random(in: 1...100))", for: UIControl.State.normal)
dummyButton.translatesAutoresizingMaskIntoConstraints = false
dummyButton.addTarget(self, action: #selector(refreshSection), for: UIControl.Event.touchUpInside)
let headerViewHeight = table.tableHeaderView?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height ?? 0
if scrollView.contentOffset.y >= headerViewHeight {
addToHeader(header: header, addonView: dummyButton, height: 44, width: 80)
}else{
if sectionHeaderStickyTop == false {
sectionHeaderStickyTop = true
sectionHeader.translatesAutoresizingMaskIntoConstraints = true
header.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin]
header.frame = CGRect(x: 0, y: 0, width: header.bounds.width, height: header.bounds.height)
sectionHeaderContainer.addSubview(sectionHeader)
}
dummyButton.removeFromSuperview()
}
tableView.setNeedsLayout()
}