使用Realm Objects滚动到UITableView中的最新插入行

问题描述 投票:0回答:2

我有以下代码正常工作,它从Realm列表中获取一个名为groceryList的项目列表,并根据productName以降序显示在UITableView上。我希望能够做的是滚动到表格中最新插入的行/项目,现在当插入新项目时,用户可能看不到它,因为项目按字母顺序重新排序,并且最新项目可能不可见在tableView上。

如何滚动到UITableView中最新插入的行/项?

领域对象:

    class Item:Object{
        @objc dynamic var productName:String = ""
        @objc dynamic var isItemActive = true
        @objc dynamic var createdAt = NSDate()
    }

    class ItemList: Object {
        @objc dynamic var listName = ""
        @objc dynamic var createdAt = NSDate()
        let items = List<Item>()
    }

UITableView的:

    class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{

        var allItems : Results<Item>!
        var groceryList : ItemList!

        override func viewDidLoad() {
            super.viewDidLoad()
            groceryList = realm.objects(ItemList.self).filter("listName = %@", "groceryList").first              
            updateResultsList()
        }

        func updateResultsList(){
            if let list = groceryList{
                allItems  = activeList.items.sorted(byKeyPath: "productName", ascending: false)
            }
        }

        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return allItems.count
        }
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {       
            let cell = tableView.dequeueReusableCell(withIdentifier: "reusableCell", for: indexPath) as! CustomCell       
            let data = allItems[indexPath.row]      
            cell.displayProductName.text = data.productName
            return cell
        }  
    }
ios swift uitableview realm
2个回答
3
投票

您可以使用Realm通知来了解数据源Results何时被修改,然后从那里更新您的表视图并进行滚动。

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    var allItems: Results<Item>!
    var groceryList: ItemList!

    var notificationToken: NotificationToken? = nil

    deinit {
        notificationToken?.invalidate()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        groceryList = realm.objects(ItemList.self).filter("listName = %@", "groceryList").first
        updateResultsList()
        observeGroceryList
    }

    func updateResultsList(){
        if let list = groceryList {
            allItems  = activeList.items.sorted(byKeyPath: "productName", ascending: false)
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allItems.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reusableCell", for: indexPath) as! CustomCell
        let data = allItems[indexPath.row]
        cell.displayProductName.text = data.productName
        return cell
    }

    func observeGroceryList() {
        notificationToken = allItems.observe { [weak self] (changes: RealmCollectionChange) in
            switch changes {
            case .initial:
                self?.tableView.reloadData()
            case .update(_, let deletions, let insertions, let modifications):
                // Query results have changed, so apply them to the UITableView
                self?.tableView.beginUpdates()
                self?.tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }),
                                     with: .automatic)
                self?.tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}),
                                     with: .automatic)
                self?.tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }),
                                     with: .automatic)
                self?.tableView.endUpdates()
                if let lastInsertedRow = insertions.last {
                    self?.tableView.scrollToRow(at: insertions.last, at: .none, animated: true)
                }
            case .error(let error):
                // An error occurred while opening the Realm file on the background worker thread
                print("\(error)")
            }
        }
    }
}

1
投票

添加以下代码作为tableview的扩展。

extension UITableView {
    func scrollToBottom() {
        let sections = numberOfSections-1
        if sections >= 0 {
            let rows = numberOfRows(inSection: sections)-1
            if rows >= 0 {
                let indexPath = IndexPath(row: rows, section: sections)
                DispatchQueue.main.async { [weak self] in
                    self?.scrollToRow(at: indexPath, at: .bottom, animated: true)
                }
            }
        }
    }
}

现在只需在您的方法中使用它:

func updateResultsList(){
       if let list = groceryList{
             allItems  = activeList.items.sorted(byKeyPath: "productName", ascending: false
             yourTableView.scrollToBottom()
      }
 }

只需在您想要的地方使用此方法,就应该向下滚动。

yourTableView.scrollToBottom()
© www.soinside.com 2019 - 2024. All rights reserved.