微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ScrollToRow - 如何让最后一行滚动到屏幕顶部?

如何解决ScrollToRow - 如何让最后一行滚动到屏幕顶部?

我在tableView.scrollToRow方法的内部使用didSelectRowAt,以便在选择行时,视图会自动将下一行滚动到屏幕的顶部。我让它工作正常,但我不知道当屏幕上有足够的空间来容纳所有内容时如何处理最后几行。

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

Example

这是我的相关代码

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(或其他地方)以将最后一行滚动到顶部的内容,即使所有内容都适合屏幕?

解决方法

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

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

感谢 @SPatel 和 @congnd 提供的意见,从而得出了这个答案。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。