UITableView - How to keep table rows fixed as user scrolls

后端 未结 3 2059
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 15:29

I\'d like to be able to fix the position of certain rows in a UITableView as the user scrolls.

Specifically, I have a table whereby certain rows are \"headers\" for

3条回答
  •  青春惊慌失措
    2020-12-24 16:02

    Swift 5 solution

    var header: UIView?
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(indexPath: indexPath) as UITableViewCell
        header = cell.contentView
        return cell
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let headerCell = tableView.cellForRow(at: IndexPath(row: 0, section: 0))
        guard headerCell == nil || (headerCell!.frame.origin.y < self.tableView.contentOffset.y + headerCell!.frame.height/2) else {
            header?.isHidden = true
            return
        }
        guard let hdr = header else { return }
        hdr.isHidden = false
        hdr.frame = CGRect(x: 0, y: tableView.contentOffset.y, width: hdr.frame.size.width, height: hdr.frame.size.height)
        if !tableView.subviews.contains(hdr) {
            tableView.addSubview(hdr)
        }
        tableView.bringSubviewToFront(hdr)
    }
    

提交回复
热议问题