如何使用Model NSObject类和MVVM重新加载TableVIew

时间:2019-03-09 17:51:53

标签: ios swift mvvm tableview

我想重新加载不使用tableview.reloadData()方法的TableView,因为我使用了MVVM结构,所以我将模型类附加到情节提要,问题是我的tableview首先被重新加载,然后我得到了所有数据我该如何解决这个问题,如果有人有解决方案,请帮助我!!

这是情节提要模型附件

enter image description here

型号代码:-

class MovieModel: Decodable{

    var artistName: String = ""
    var trackName: String = ""

    init(artistName: String, trackName: String){
        self.artistName = artistName
        self.trackName = trackName
    }

}

class ResultModel: Decodable{

    var results = [MovieModel]()

    init(results: [MovieModel]) {
        self.results = results
    }
}

我的ViewModel文件代码:-

class MovieViewModel: NSObject {

    var artistName: String = ""
    var trackName: String = ""
    var movieModel: MovieModel?
     var movieData = [MovieViewModel]()

    override init() {

    }

    init(movie: MovieModel) {
        self.artistName = movie.artistName
        self.trackName = movie.trackName
    }

    func getData(){
        Service.shareInstance.getAllMovieData { (movie, error) in
            if error == nil{
                self.movieData = movie?.map({return MovieViewModel(movie: $0)}) ?? []
                print(self.movieData)
            }else{
                print("\(String(describing: error))")
            }
        }
    }

    func numberOfRow(section:Int) -> Int{
        return movieData.count
    }

    func cellForRow(indexPath: IndexPath) -> MovieViewModel{
        return self.movieData[indexPath.row]
    }


}

我的ViewController代码:-

class ViewController: UIViewController {

    @IBOutlet var movieVM: MovieViewModel?
    @IBOutlet var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
            self.movieVM?.getData()
    }
}

extension ViewController: UITableViewDelegate, UITableViewDataSource{

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return movieVM?.numberOfRow(section: section) ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
        let movie = movieVM?.cellForRow(indexPath: indexPath)
        cell?.textLabel?.text = movie?.artistName
        cell?.detailTextLabel?.text = movie?.trackName
        return cell!
    }

}

就我而言,我不会重新加载tableview,所有这些操作都是使用ModelClass完成的!谢谢!

0 个答案:

没有答案