使用swift3中的mvvm方法在textfield中搜索函数

时间:2018-05-03 10:37:59

标签: ios

如何在swift3中使用mvvm方法在textfield中进行搜索功能。 我已经从api中列出了tableview中的数据。但是我需要在textfield action上实现搜索tableview。如何查看viewmodel和viewcontroller。

我的viewmodel: -

class ViewModel: NSObject {


    var datasourceModel:DataSourceModel



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


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

    }

    func numberOfRowsInSection(section:Int) -> Int {

        return (datasourceModel.dataListArray?.count)!
    }

    func search(completion :@escaping (_ isSearching:Bool) -> ()) {


        loadFromWebserviceData { (newDataSourceModel) in

        if(newDataSourceModel != nil)
        {




        self.datasourceModel = newDataSourceModel!
        completion(true)

        }
        else{
        completion(false)
        }
        }

    }


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


        loadFromWebserviceData { (newDataSourceModel) in

            if(newDataSourceModel != nil)
            {




                self.datasourceModel = newDataSourceModel!
                completion(true)

            }
            else{
                completion(false)
            }
        }
    }


    //}
    func loadFromWebserviceData(completion :@escaping (DataSourceModel?) -> ()){

        //with using Alamofire  ..............

        Alamofire.request("http://www.example").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:DataSourceModel = DataSourceModel(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 ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource, UISearchBarDelegate,UITextFieldDelegate {


    @IBOutlet private weak var tableView: UITableView!

    @IBOutlet weak var txt: UITextField!






    private var searchViewModel :ViewModel!

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?, withViewModel viewModel:ViewModel) {

        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()



        self.title = "SEARCH"


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



     searchViewModel.loadData { (isSuccess) in


            if(isSuccess == true)
            {


                self.tableView.reloadData()



          }
           else{


                }
        }


    }


    @objc private func textFieldDidChange(textField: UITextField) {


       if textField.text == "" {



       self .viewDidLoad()
      }








        else{
            filterContentForSearchText(searchText: textField.text!)
       }
    }


    func filterContentForSearchText(searchText: String) {






        tableView.reloadData()
    }


    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? QM_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))



        return cell
    }


  and my datasource:-



  var dataListArray:Array<Model>? = []


    init(array :Array<[String:Any]>?) {
        super.init()
        var newArray:Array<[String:Any]> = []
        if array == nil{

         //   newArray = self.getJsonDataStored44()
        }
        else{
            newArray = array!

        }

        var datalist:Array<Model> = []
        for dict in newArray{

            let model = Model(dictionary: dict)

            datalist.append(model)
        }
        self.dataListArray = datalist


          }



}

这是我的代码..所以viewmodel中需要的更改是什么,tableview中的部分没有,tableview中的行的单元格以及单击textfeild时的函数。

0 个答案:

没有答案