简体   繁体   中英

iOS UITableView scrolling insets while filtering

I have some problem with UITableView scrolling. This is my simple screen where I have UITextField and UITableView with cells. When user type something in UITextField app filters list of items and reloads UITableView. And it is working as expected.

在此处输入图片说明

On the right screen you can see how UITableView looks when I scroll. Cells go under UITextField.

Let's assume I scrolled some cell and If I start to type something in UITextField I got list of filtered cells but some of them are under UITextField and I can't scroll them down.

在此处输入图片说明

By default the table's scroll offset doesn't change when you reload the table with new set of row data. You need to scroll back to top after reloading the table :

self.tableView.scrollToRow(at: IndexPath(row: 0, section: 0),
                                   at: .top,
                                   animated: true)

and if you don't have a default place-holder cell to represent "No Matching Results" when there are no results and thus no cells to represent at Index (0,0) then add following condition before the above code to safeguard a crash:

guard cellResults.count > 0 else { return }

First of all your UITextField contained on tableview header view? UITableView need scrolling with table or not? If your need always show first cell when user input something in UITextField, i recommend it with RxSwift like this

textField
    .rx.text
    .orEmpty
    .debounce(0.1, scheduler: MainScheduler.instance)
    .distinctUntilChanged()
    .subscribe(onNext: { [unowned self] query in
        //TODO: Do something with you table, for example 
        // self.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
        // or update tableView. 
    })
    .disposed(by: disposeBag)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM