简体   繁体   中英

Swift: Avoid scrolling top 2 tableview cells

Is there a way to stop scrolling certain cells in tableview? I want the top 2 cells in UITableView to be static and have scroll enabled on other cells. Scroll enabled property is on tableview, so it scrolls all the cells.

The top 2 cells are of height 44.0 each. I tried the below code, but it still scrolls the top 2 cells.

func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    isScrolling = true
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let startScrollingOffset = 88.0
    if (scrollView.contentOffset.y < CGFloat(startScrollingOffset)) {
        // moved to top
        isScrollDown = false
    } else if (scrollView.contentOffset.y > CGFloat(startScrollingOffset)) {
        // moved to bottom
        isScrollDown = true
    } else {
        // didn't move
    }
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    if isScrollDown == false {
        return
    }
}

If you're trying to achieve an effect like static cells that remain on top when the list scrolls, use header view property of UITableView , here is an example with minimum code required to make this work. Replace the headerView with whatever cells you're trying to not scroll.

class VC: UITableViewController {

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.backgroundColor = .purple
        return headerView
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = String(describing: indexPath)
        return cell
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20
    }
}

The solution could be take out first two row data from your data source( may be an array) and and create a custom view with that two row data. then set the custom view in the tableviewHeader using viewForHeaderInSection

As you have already removed first two row your table will show the data from third entry and the first two will be in top of them as header.

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