结构化数据的搜索栏Swift 4

时间:2018-05-10 19:10:17

标签: ios swift uitableview uisearchbar

我对swift很新......我有一个像这样的数据模型类:

class PostDataModel: NSObject {

    var postID : Int = 0
    var postTitle : String = ""
    var postExcerpt : String = ""
    var postContent : String = ""
    var postThumbnailURL : String = ""
    var postUpdated : String = ""
    var postLink : String = ""
    var postSlug : String = ""
}

我需要在postTitle中搜索在视图控制器中显示的搜索栏中编辑的文本:

//MARK: - Search bar methods inside the view controller

extension ViewController: UISearchBarDelegate {

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        print(searchBar.text!)
        shouldShowSearchResults = true
        filteredTableData = postsArray.filter({$0.postTitle == searchBar.text})

        tablePosts.reloadData()
    }

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

        if searchBar.text == nil || searchBar.text == "" {

            shouldShowSearchResults = false
            view.endEditing(true)

            tablePosts.reloadData()
        } else {

            shouldShowSearchResults = true
            filteredTableData = postsArray.filter({(item)  -> Bool in
              var stringMatch = item.postTitle.lowercased().range(of: searchBar.text!)
                return stringMatch != nil ? true : false
            })
            tablePosts.reloadData()
        }
    }
}

搜索时,我发现解决方案只有在String中搜索文本时,但如何根据标题中包含的文本过滤PostDataModel数组?

非常感谢。

1 个答案:

答案 0 :(得分:0)

searchBar.text中也使用小写文字。

var stringMatch = item.postTitle.lowercased().range(of: searchBar.text!.lowercased())