ios - UITableView 导航后滚动到选定的单元格

标签 ios swift uitableview

我有一个 TableView ,它从后端获取远程数据,一切正常,我想要完成的是当用户单击任何单元格以导航到其他 ViewController(详细信息 Controller )并按下后退按钮时 TableView 应该滚动到选定的单元格而不是返回顶部 我试过 tableView.scrollToRow 如下所示,但它不起作用?我知道我在我的加载数据函数中调用 tableView.reloadData() 否则它不会加载

class feeds: UITableViewController {
    var data = [AnyObject]()
    override func viewDidLoad() {
        super.viewDidLoad()

        LoadData()
    }


    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

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

        return data.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

       // configur tabl cell

        return cell
    }

    func LoadData(){

    // Fetch Feeds to dataArray 
        // Reload UITable View
        self.tableView.reloadData()
        let celloffset = UserDefaults.standard.integer(forKey: "celloffset")
        if celloffset != 0{
        let index = IndexPath(item: celloffset, section: 0)
        self.tableView.scrollToRow(at: index, at: UITableViewScrollPosition.middle, animated: false)
        }
    }


    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        UserDefaults.standard.set(indexPath.row, forKey: "celloffset")

        // Navigate to Details VC
    }

}

任何帮助或想法将不胜感激

最佳答案

当您返回初始 View Controller 时,您不需要再次获取数据。只需使用 ViewWillAppear 方法。获取 celloffset 并滚动 TableView 。

let celloffset = UserDefaults.standard.integer(forKey: "celloffset")
if celloffset != 0{
let index = IndexPath(item: celloffset, section: 0)
self.tableView.scrollToRow(at: index, at: UITableViewScrollPosition.middle, animated: false)}

关于ios - UITableView 导航后滚动到选定的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44230895/

相关文章:

ios - Office 365 SharePoint 列表通知新项目

ios - 如何使用 swift 显示和/或隐藏 subview

ios - UIPageController : Turning the page forward then backward quickly only updates the first page

ios - AND 和 OR 与 NSPredicate 结合。 iOS swift

swift - 以编程方式将按钮放在一起

ios - 单击 tableView 单元格时保留 tabController 的已加载 View 部分?

ios - 在单元格和水平滚动之间滑动冲突

ios - 如何在 Firebase 中省略观察节点的子节点?

ios - 选择时导航栏中的 UIBarButtonItem 会突出显示,但工具栏中的 UIBarButtonItem 不会

iphone - 如何设置自定义规则,例如 GameCenter 寻找比赛的难度级别