【问题标题】:Swift: Avoid scrolling top 2 tableview cellsSwift:避免滚动前 2 个表格视图单元格
【发布时间】:2020-09-16 04:23:41
【问题描述】:

有没有办法停止滚动表格视图中的某些单元格?我希望 UITableView 中的前 2 个单元格是静态的,并在其他单元格上启用滚动。 Scroll enabled 属性位于 tableview 上,因此它会滚动所有单元格。

前 2 个单元格的高度各为 44.0。我尝试了下面的代码,但它仍然会滚动前 2 个单元格。

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
    }
}

【问题讨论】:

    标签: ios swift uitableview uiscrollview


    【解决方案1】:

    如果您想实现在列表滚动时保持在顶部的静态单元格之类的效果,请使用 UITableView 的标题视图属性,这里有一个示例,所需代码最少。将 headerView 替换为您尝试不滚动的任何单元格。

    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
        }
    }
    

    【讨论】:

    • 感谢科学怪人!我现在正在尝试...但是 viewForHeaderInSection 可以为同一部分返回 2 个单元格吗?
    • 只需将它们添加为子视图并对其进行约束,使它们看起来像上下两个单元格。
    【解决方案2】:

    解决方案可以从您的数据源(可能是一个数组)中取出前两行数据,并使用这两行数据创建一个自定义视图。然后使用viewForHeaderInSection在tableviewHeader中设置自定义视图

    由于您已经删除了前两行,您的表格将显示第三个条目的数据,前两个将作为标题位于它们的顶部。

    【讨论】:

      猜你喜欢
      • 2016-11-23
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多