【问题标题】:How to make first cell visible?如何使第一个单元格可见?
【发布时间】:2021-07-29 13:55:09
【问题描述】:

我有一个检测最后一个单元格的代码,但我很好奇现在如何检测 tableView 中的第一个单元格,因为在我的 tableView 中,并非所有单元格都在 iphone 7 或更少的设备上可见,这就是我必须这样做的原因使用滚动方法。

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
    let contentOffsetMaxY: Float = Float(scrollView.contentOffset.y + scrollView.bounds.size.height)
    let contentHeight: Float = Float(scrollView.contentSize.height)
    let lastCellIsVisible = contentOffsetMaxY > contentHeight
    
    
    if lastCellIsVisible {
     //some action
    }
}

【问题讨论】:

  • 这能回答你的问题吗? UITableView - scroll to the top
  • @AlexBailey 不,我不需要滚动操作到顶部,我想知道如何使用上面的代码检测所有单元格,至少对于第一个单元格。我只设法检测到最后一个单元格。而像willDisplayCell 这样的方法不起作用

标签: swift uitableview uiscrollview


【解决方案1】:

您可以使用UITableViewDelegate 中的tableView(_:willDisplay:forRowAt:)

它将在单元格显示之前被调用,并且每个单元格都会被调用一次。

您的代码如下所示:


func viewDidLoad() {
  super.viewDidLoad()
  ...
  tableView.delegate = self
  ...
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
  if indexPath.row == 0 {
    // First cell is going to be displayed
  }
  if indexPath.row == tableView.numberOfRows(inSection: indexPath.section) - 1 {
    // Last cell is going to be displayed
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    相关资源
    最近更新 更多