在tableview

时间:2018-04-30 05:58:02

标签: ios uitableview mvvm uisearchbar

textField的{​​{1}}中搜索。

我需要搜索tableView中的名字。因此,我tableView中有tableViewtextField

我需要从Api搜索。为此,我使用了Alamofire方法来获取数据。

我需要搜索。现在我实现显示从api到UIViewController的名称,我得到了输出。但我需要在tableView

中实现搜索.how

我的模特: -

mvvm

我的观看模式: -

class SearchModel: NSObject {
    var restaurantname :String!
    init?(dictionary :JSONDictionary) {

        guard let name = dictionary["name"] as? String  else {
                return
        }
        self.restaurantname = name
    }
}

我的DataSourcemodel: -

class SearchViewModel: NSObject {
        var datasourceModel:SearchDataSourceModel

        init(withdatasource  newDatasourceModel: SearchDataSourceModel) {
            datasourceModel = newDatasourceModel
        }

        func datafordisplay(atindex indexPath: IndexPath) -> SearchModel{
            return  datasourceModel.dataListArray![indexPath.row]
        }

        func numberOfRowsInSection(section:Int) -> Int {
            return (datasourceModel.dataListArray?.count)!
        }

        func loadData(completion :@escaping (_ isSucess:Bool) -> ()){
            loadFromWebserviceData { (newDataSourceModel) in

                if(newDataSourceModel != nil) {
                    self.datasourceModel = newDataSourceModel!
                    completion(true)
                }
                else {
                    completion(false)
                }
            }
        }
        //}

        func loadFromWebserviceData(completion :@escaping (SearchDataSourceModel?) -> ()) {
            //with using Alamofire  ..............
            Alamofire.request("http://www.example.com").validate(statusCode: 200..<300).validate(contentType: ["application/json"]).responseJSON{ response in

                switch response.result {
                    case .success(let data):
                        print("success",data)
                        let result = response.result
                        if     let wholedata = result.value as? [String:Any]{


                        if  let data = wholedata["data"] as? Array<[String:Any]>{
                            //  print(data["name"] as! String)
                            print(data)
                            print(response)
                            let newDataSource:SearchDataSourceModel = SearchDataSourceModel(array: data)

                            completion(newDataSource)
                            //       }
                        }
                    }
                    //  case .failure(let data):
                    //  print("fail",data)


                    case .failure(let encodingError ):
                        print(encodingError)
                        //  if response.response?.statusCode == 404 {
                            print(encodingError.localizedDescription)
                            completion(nil)
                    //   }
                }
            }}
    }

我的viewController类: -

 class SearchDataSourceModel: NSObject {
        var dataListArray:Array<SearchModel>? = []

        init(array :Array<[String:Any]>?) {
            super.init()
            var newArray:Array<[String:Any]> = []
            if array == nil {
             //   newArray = self.getJsonDataStored44()
            }
            else {
                newArray = array!
            }

            var datalist:Array<SearchModel> = []
            for dict in newArray {
                let model = SearchModel(dictionary: dict)
                datalist.append(model!)
            }
            self.dataListArray = datalist
        }
    }

tableViewCell: -

 class SearchViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

        @IBOutlet private weak var tableView: UITableView!

        private var searchViewModel :SearchViewModel!

        init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, withViewModel viewModel:SearchViewModel) {
            super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
            searchViewModel  = viewModel
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

        override func viewDidLoad() {
            super.viewDidLoad()

           //  tableView.dataSource = self
           //  filteredData = data

            searchViewModel.loadData { (isSuccess) in
            if(isSuccess == true) {
                self.tableView .reloadData()
            }
            else {
            }
            }
          //  self.tableView .reloadData()
          // Do any additional setup after loading the view.
        }

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

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let identifier = "searchcell"
            var cell: SearchCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? SearchCell

            if cell == nil {
                tableView.register(UINib(nibName: "SearchCell", bundle: nil), forCellReuseIdentifier: identifier)
                cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? SearchCell
            }
           cell.setsearchData(search: searchViewModel.datafordisplay(atindex: indexPath))
           //   cell.name.text = searchViewModel.datafordisplay(atindex: indexPath)
           //  cell.name.text = filteredData[indexPath.row]

           //   cell.setsearchData(search: searchViewModel.datafordisplay(atindex: indexPath))

           return cell
        }

       /*
         // MARK: - Navigation

         // In a storyboard-based application, you will often want to do a little preparation before navigation
         override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
         // Get the new view controller using segue.destinationViewController.
         // Pass the selected object to the new view controller.
         }
         */

    }

这是我的代码。现在如何在这里实现搜索。

2 个答案:

答案 0 :(得分:0)

有搜索方式。

  1. 输入文字并按搜索按钮
  2. 当您键入时,不使用搜索按钮进行搜索。
  3. 解决方案1:

    您需要在搜索按钮上调用方法

    搜索按钮。

    enum

    第二个解决方案

    func Search() {
            predicate = NSPredicate(format: "Self.YourSearchListName beginsWith[c]%@", SearchName)
            GetsearchList = YourArrayForSearch.filtered(using: predicate) as NSArray
    
            YourTable.reloadData()
        }
    

    for 2nd Solution不要忘记设置委托。

答案 1 :(得分:0)

filteredContactListArray是当用户开始搜索特定文本时,保存已过滤数据的数组以重新加载tableview。

@IBOutlet var searchCityTextField: UITextField!
var filteredSearchArray :SearchViewModel!

在Viewdidload()函数中

searchCityTextField.addTarget(self, action: #selector(textFieldDidChange(textField:)), for: UIControlEvents.editingChanged)

UItextfieldDelegate方法

func textFieldDidChange(textField: UITextField) {
        if textField.text == "" {
            filteredSearchArray = searchViewModel// contactListArray is the actual array with all the list of data.
            citiesTableView.reloadData()
        }else{
            filterContentForSearchText(textField.text!)
        }
}

func filterContentForSearchText(searchText: String) {
        filteredSearchArray = NSMutableArray(array:searchViewModel. dataListArray.filter({(ele:AnyObject) -> Bool in
            return (ele as! searchViewModel).cityName.lowercased().contains(searchText.lowercased())
        }))
        citiesTableView.reloadData()
}

UItableviewDelegate方法

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