简体   繁体   中英

How to make tableView cell “stick” while scrolling

I have a SegmentedControl on a Cell at the top of my tableView (the tableView consists of all static cells)...I want the top cell (and segmentedControl) to "stick" so that it is always visible as a user scrolls through the table (see screenshot below). Is this possible?

在此处输入图片说明

Usually, for applying this behavior you should add it as a header view instead of a cell. Header views in table view does "stick". But since you are adding static cells (UITableViewController), even if you tried to add a header view to the table view it won't apply the sticking behavior.

As a workaround you might need to add a new UIViewController contains a view on the top (the header view) and a container view, as follows:

在此处输入图片说明

The one hackish solution which pops to my mind is:

Declare header in your VC, or hold the reference:

private var header: UIView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40))

Add it as a subview of tableView and set content inset equal to height of the header.

tableView.addSubview(header)
tableView.contentInset.top = header.frame.height

If your header use autolayout you will need to call view.layoutIfNeeded() before setting content inset

and then for header to stick always to the top of tableView:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    header.frame.origin.y = scrollView.contentOffset.y
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM