【问题标题】:ScrollToRow - How to get last rows to scroll to top of screen?ScrollToRow - 如何让最后一行滚动到屏幕顶部?
【发布时间】:2021-04-05 16:16:47
【问题描述】:

我在@ 987654324中使用tableView.scrollToRow方法,以便在选择行时,视图会自动将下一行滚动到屏幕的顶部。我让它工作得很好,除了当屏幕上有足够的空间容纳所有东西时,我不确定如何处理最后几行。

在下面的示例中,单击第 5 步之后会显示我所描述的场景。

这是我的相关代码:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let topInstruction = arrayOne[currentArrayOneIndex!].instructions![topInstructionIndex]
        print(topInstructionIndex)
        print(arrayOne[currentArrayOneIndex!].instructions!.count)
        
        // Check if it is the last instruction
        if topInstructionIndex < arrayOne[currentArrayOneIndex!].instructions!.count {
            
            // Change cell colour to green
            let tappedInstruction = tableView.cellForRow(at: indexPath)
            tappedInstruction?.contentView.backgroundColor =  #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
            
            topInstructionIndex += 1
            
            // Scroll to the next instruction
            let nextInstruction = IndexPath(row: topInstructionIndex, section: 0)
            tableView.scrollToRow(at: nextInstruction, at: UITableView.ScrollPosition.top, animated: true)
            return
            
        }
        else {
            // Finish the instructions
            print("This is the last instruction.")
            return
        }

    }

有什么我可以添加到didSelectRowAt(或其他地方)以将最后一行滚动到顶部,即使所有内容都适合屏幕?

【问题讨论】:

  • 使用 contentInsets(bottom = tableview.bound.height)
  • 你可以考虑设置contentInsets或者在tableview的底部添加一个空单元格。
  • 谢谢@SPatel 和@congnd!那是完全正确的。现在发布答案。

标签: ios swift uitableview didselectrowatindexpath scroll-position


【解决方案1】:

将以下代码添加到 cellForRowAt 方法就可以了。

tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 500, right: 0)

感谢 @SPatel 和 @congnd 提供了导致此答案的 cmets。

【讨论】:

    猜你喜欢
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    相关资源
    最近更新 更多