首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UISearchBar in UITableView

UISearchBar in UITableView
EN

Stack Overflow用户
提问于 2018-12-11 04:47:56
回答 1查看 2.7K关注 0票数 1

我使用RxSwift在我的表视图中显示人员列表,我的tableview有两个部分,第一部分是旧搜索,第二个部分是all Person。现在,当用户在UISearchBar的textfield上键入名称时,我不知道应该如何过滤Person。

这是我的人偶模型:

代码语言:javascript
复制
struct PersonModel {
    let name: String
    let family:String
    let isHistory:Bool
}

这是我的ContactsViewModel

代码语言:javascript
复制
struct SectionOfPersons {
    var header: String
    var items: [Item]
}

extension SectionOfPersons: SectionModelType {
    typealias Item = PersonModel

    init(original: SectionOfPersons, items: [SectionOfPersons.Item]) {
        self = original
        self.items = items
    }
}

class ContactsViewModel {

    let items = PublishSubject<[SectionOfPersons]>()

    func fetchData(){

        var subItems : [SectionOfPersons] = []

        subItems.append( SectionOfPersons(header: "History", items: [
            SectionOfPersons.Item(name:"Michelle", family:"Obama", isHistory:true ),
            SectionOfPersons.Item(name:"Joanna", family:"Gaines", isHistory:true )
        ]))
        subItems.append( SectionOfPersons(header: "All", items: [
            SectionOfPersons.Item(name:"Michelle", family:"Obama", isHistory:false ),
            SectionOfPersons.Item(name:"James", family:"Patterson", isHistory:false ),
            SectionOfPersons.Item(name:"Stephen", family:"King", isHistory:false ),
            SectionOfPersons.Item(name:"Joanna", family:"Gaines", isHistory:false )
        ]))

        self.items.onNext( subItems )
    }

}

这是我的ContactsViewController:

代码语言:javascript
复制
class ContactsViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!

    private lazy var dataSource = RxTableViewSectionedReloadDataSource<SectionOfPersons>(configureCell: configureCell, titleForHeaderInSection: titleForHeaderInSection)

    private lazy var configureCell: RxTableViewSectionedReloadDataSource<SectionOfPersons>.ConfigureCell = { [weak self] (dataSource, tableView, indexPath, contact) in
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "ContactTableViewCell", for: indexPath) as? ContactTableViewCell else { return UITableViewCell() }
        cell.contact = contact
        return cell
    }

    private lazy var titleForHeaderInSection: RxTableViewSectionedReloadDataSource<SectionOfPersons>.TitleForHeaderInSection = { [weak self] (dataSource, indexPath) in
        return dataSource.sectionModels[indexPath].header
    }

    private let viewModel = ContactsViewModel()
    private let disposeBag = DisposeBag()

    var showContacts = PublishSubject<[SectionOfPersons]>()
    var allContacts = PublishSubject<[SectionOfPersons]>()

    override func viewDidLoad() {
        super.viewDidLoad()

        bindViewModel()
        viewModel.fetchData()
    }

    func bindViewModel(){

        tableView.backgroundColor = .clear
        tableView.register(UINib(nibName: "ContactTableViewCell", bundle: nil), forCellReuseIdentifier: "ContactTableViewCell")
        tableView.rx.setDelegate(self).disposed(by: disposeBag)

        viewModel.items.bind(to: allContacts).disposed(by: disposeBag)
        viewModel.items.bind(to: showContacts).disposed(by: disposeBag)
        showContacts.bind(to: tableView.rx.items(dataSource: dataSource)).disposed(by: disposeBag)

        searchBar
            .rx.text
            .orEmpty
            .debounce(0.5, scheduler: MainScheduler.instance)
            .distinctUntilChanged()
            .filter { !$0.isEmpty }
            .subscribe(onNext: { [unowned self] query in

                ////// if my datasource was simple string I cand do this
                self.showContacts = self.allContacts.filter { $0.first?.hasPrefix(query) } // if datasource was simple array string, but what about complex custome object?!

            })
            .addDisposableTo(disposeBag)

    }
}

谢谢你的回应。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-11 13:16:36

您不需要在您的ContactsViewController中使用两个ContactsViewController。您可以将从UISearchBar和viewModel获得的可观测值直接绑定到UITableView。若要使用查询筛选联系人,您必须分别筛选每个区段。我用了一个小助手函数。

所以我就是这么做的

  1. 去掉showContactsallContacts属性
  2. 创建一个可观察到的query,它发出用户输入到搜索栏中的文本(不要过滤掉空文本,当用户删除搜索栏中的文本时,我们需要它来恢复所有联系人)
  3. 将可观测的query和可观测的viewModel.items组合成一个可观测的
  4. 使用此可观察到的方法过滤查询中的所有联系人。
  5. 将可观察到的数据绑定到表视图rx.items

我使用了combineLatest,所以每当查询或viewModel.items更改时,表视图就会更新(我不知道所有联系人的列表是静态的还是添加/删除联系人)。

现在,您的bindViewModel()代码看起来如下(我将tableView.register(...)移到了viewDidLoad):

代码语言:javascript
复制
func bindViewModel(){
    let query = searchBar.rx.text
        .orEmpty
        .distinctUntilChanged()

    Observable.combineLatest(viewModel.items, query) { [unowned self] (allContacts, query) -> [SectionOfPersons] in
            return self.filteredContacts(with: allContacts, query: query)
        }
        .bind(to: tableView.rx.items(dataSource: dataSource))
        .disposed(by: disposeBag)
}  

下面是使用查询过滤所有联系人的函数:

代码语言:javascript
复制
func filteredContacts(with allContacts: [SectionOfPersons], query: String) -> [SectionOfPersons] {
    guard !query.isEmpty else { return allContacts }

    var filteredContacts: [SectionOfPersons] = []
    for section in allContacts {
        let filteredItems = section.items.filter { $0.name.hasPrefix(query) || $0.family.hasPrefix(query) }
        if !filteredItems.isEmpty {
            filteredContacts.append(SectionOfPersons(header: section.header, items: filteredItems))
        }
    }
    return filteredContacts
}

我以为您想要根据查询检查人员的姓名和家庭。

还有一件事:我删除了debounce,因为您筛选了一个已经在内存中的列表,它非常快。在搜索栏中键入触发网络请求时,通常使用debounce

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53717518

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档