【问题标题】:Return autosuggestion search with swift xcode使用 swift xcode 返回自动建议搜索
【发布时间】:2018-09-30 11:01:26
【问题描述】:

我有一个搜索栏,可以过滤食谱标题的 xml 数组。问题是我必须搜索整个标题,否则我看不到建议的结果。例如,如果我有“Whole Grain Waffles”和“Whole Wheat Bread”,输入“Whole”不会返回任何结果。键入“Whole Grain Waffles”成功返回。这是searchBar 函数

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    if searchBar.text == nil || searchBar.text == "" {
        isSearching = false
        view.endEditing(true)
        myTableView.reloadData()
    } else {
        isSearching = true
        filteredData = tableViewDataSource.filter({$0.title == searchBar.text})
        myTableView.reloadData()
    }

}

我很确定解决方案与区分大小写有关,并在设置 filteredData 时返回某些字符。提前感谢您的帮助

【问题讨论】:

    标签: swift xml xcode search filter


    【解决方案1】:

    使用range 在我的情况下工作

    filteredData = tableViewDataSource.filter({$0.title.range(of: searchBar.text!) != nil})
    

    【讨论】:

      【解决方案2】:

      您可以使用contains 过滤数组中包含文本的任何项目,或者如果您想搜索以搜索文本开头的字符串,也可以使用hasPrefix

      类似的,

      filteredData  = tableViewDataSource.filter { $0.title.contains(searchBar.text) ?? "" }
      

      或者,

      filteredData = tableViewDataSource.filter { $0.title.hasPrefix(searchBar.text) ?? "" }
      

      【讨论】:

      • 我在网上看到过类似的答案,但有对象类型兼容性错误,例如“无法转换类型'String?'的值?”到预期的参数类型'String.Element'(又名'Character')”。我发现范围有效
      • 你使用的是什么版本的 Swift?
      • 目前使用的是swift 4.0
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 2017-01-26
      相关资源
      最近更新 更多