从单独类的二维数组输出元素

时间:2018-12-07 05:04:50

标签: ios swift uitableview

我需要将二维数组中的第二个元素从一个类输出到TableViewController。我已经尝试了几件事,例如data.reduce into :,但是没有运气。应该将FirstViewController填充为三种类型的“动作,悬念和浪漫”,然后可以单击它们以显示属于该类型的所有电影。

头等舱:

     import Foundation

        protocol MovieModelDelegate: class {
           func didRecieveDataUpdate(data: [[String]])
        }

        class MovieModel {

           weak var delegate: MovieModelDelegate?

           var genreArray: [String] = []
           let data: [[String]] = [
              ["Avatar", "Action"],
              ["Limitless", "Suspense"],
              ["Die Hard", "Action"],
              ["The Avengers", "Action"],
              ["The Notebook", "Romance"],
              ["Lakehouse", "Romance"],
              ["Gone Girl", "Suspense"],
              ["Deadpool", "Action"],
              ["Passengers", "Suspense"],
              ["Inception", "Suspense"],
              ["Mission Impossible", "Action"]
         ]

          func requestData() {
             let movie: [[String]] = data
             delegate?.didRecieveDataUpdate(data: movie)
          }
       }


**TableView Class:**


    class FirstTableView: UITableViewController, MovieModelDelegate {

       var model = MovieModel()
       var selectedGenre: String = ""

       override func viewDidLoad() {
          super.viewDidLoad()
          model.delegate = self
          model.requestData()
       }

       override func numberOfSections(in tableView: UITableView) -> Int {
          return 1
       }

       override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
          return model.genreArray.count
       }

       override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          let cell = tableView.dequeueReusableCell(withIdentifier: "GenreCells", for: indexPath) as! TableViewCell
          cell.genreLabel?.text = model.genreArray[indexPath.item]
          return cell
       }

       override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
          selectedGenre = model.data[indexPath.row]
          selectedGenre = ""
          for indexPath in model.data{
              if indexPath[1] == selectedGenre{
                  selectedGenre.append(indexPath[0])
              }
          }
      }

      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
          if (segue.identifier == "pushToMovies") {
              if let VC = segue.destination as? FilteredSelection {
                  VC.selectedMovies = [selectedGenre]
              }
          }
      }

      func didRecieveDataUpdate(data: [[String]]) {
      }

      deinit{
      }
  }

2 个答案:

答案 0 :(得分:0)

您可以使用Set来获取所有流派,而不必重复。

  1. 我认识到您想用TableViewmodel.genreArray中显示流派,但是您的genreArray始终为空,因为您从未向其添加数据。
  2. 第二件事:在您的TableViewController中 实现了didReciveDataUpdate函数,但您没有做 一切都有。

头等舱:

 import Foundation
    protocol MovieModelDelegate: class {
       func didRecieveDataUpdate(data: [[String]])
    }

    class MovieModel {

       weak var delegate: MovieModelDelegate?


       let data: [[String]] = [
          ["Avatar", "Action"],
          ["Limitless", "Suspense"],
          ["Die Hard", "Action"],
          ["The Avengers", "Action"],
          ["The Notebook", "Romance"],
          ["Lakehouse", "Romance"],
          ["Gone Girl", "Suspense"],
          ["Deadpool", "Action"],
          ["Passengers", "Suspense"],
          ["Inception", "Suspense"],
          ["Mission Impossible", "Action"]
     ]

     private var genres = [String]()

     public init() {
     for dataSet in data {
        self.genres.append(dataSet[1])
     }

     //this will generate a array with only uniqe genres
     var genreArray = Array(Set(self.genres))

     }

      func requestData() {
         let movie: [[String]] = data
         delegate?.didRecieveDataUpdate(data: movie)
      }
   }

FirstTableView类:

查看didReciveDataUpdate函数

 class FirstTableView: UITableViewController, MovieModelDelegate {

   var model = MovieModel()
   var selectedGenre: String = ""

   override func viewDidLoad() {
      super.viewDidLoad()
      model.delegate = self
      model.requestData()
   }

   override func numberOfSections(in tableView: UITableView) -> Int {
      return 1
   }

   override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return model.genreArray.count
   }

   override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "GenreCells", for: indexPath) as! TableViewCell
      cell.genreLabel?.text = model.genreArray[indexPath.row]
      return cell
   }

   override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     //To get the Genre
      selectedGenre = model.data[indexPath.row][1]

      for indexPath in model.data{
          if indexPath[1] == selectedGenre{
              selectedGenre.append(indexPath[0])
          }
      }
  }

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if (segue.identifier == "pushToMovies") {
          if let VC = segue.destination as? FilteredSelection {
              VC.selectedMovies = [selectedGenre]
          }
      }
  }

  func didRecieveDataUpdate(data: [[String]]) {
     //=================here you need to update your tableView===================
  }

  deinit{
  }

}

答案 1 :(得分:0)

您需要将数据更改为可以由表视图索引的形式。我将使用以下代码将其更改为字典。

let genreDictionary = data.reduce(into: [:]) { d, element in
    d[element[1], default: []].append(element[0])
}

这将创建以下字典

["Suspense": ["Limitless", "Gone Girl", "Passengers", "Inception"], 
 "Romance": ["The Notebook", "Lakehouse"], 
 "Action": ["Avatar", "Die Hard", "The Avengers", "Deadpool", "Mission Impossible"]]

然后在tableview函数中,按以下方式使用字典

   override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return model.genreDictionary.count
   }

   override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell = tableView.dequeueReusableCell(withIdentifier: "GenreCells", for: indexPath) as! TableViewCell
      let d = model.genreDictionary
      cell.genreLabel?.text = d[d.keys.index(d.startIndex, offsetBy: indexPath.row)].key
      return cell
   }

当您需要在特定的tableview行中使用电影阵列时,可以使用以下

let d = model.genreDictionary
let arrayOfFilms = d[d.keys.index(d.startIndex, offsetBy: indexPath.row)].value