TableviewCell中的CollectionView:使用带有MVC模型的Alamofire和SwiftyJSON显示数据

时间:2019-01-18 14:50:15

标签: ios swift uitableview uicollectionview tableview

我搜索了论坛,但找不到适合我问题的解决方案,所以我决定打开一个主题。

我在Tableviewcell中有一个Collectionview。使用Alamofire和SwiftJSON,我下载数据并将其存储在模型项目中。我有2个模型文件,一个用于表视图,一个用于collectionview

用于Tableview的模型项目:

class Matchs {
    var matchTime : String
    var matchMbs : Int
    var matchLeague : String
    var matchCode : Int
    var matchHomeTeam : String
    var matchAwayTeam : String

    init(time : String, mbs : Int, league : String, code : Int, homeTeam : String, awayTeam : String ) {

        matchTime = time
        matchMbs = mbs
        matchLeague = league
        matchCode = code
        matchHomeTeam = homeTeam
        matchAwayTeam = awayTeam

    }
}

Collectionview的模型项目:

class MatchsOdds {

    var homeWin : Double
    var awayWin : Double
    var draw : Double
    var under : Double
    var over : Double
    var oddResult = ["1","0","2","Under","Over"]

    init(homeWin: Double, awayWin : Double, draw : Double, under : Double, over : Double) {
        self.homeWin = homeWin
        self.awayWin = awayWin
        self.draw = draw
        self.under = under
        self.over = over
    }

}

这是Viewcontroller代码:

class MainViewController: UIViewController {

  @IBOutlet weak var tableview: UITableView!



    let MATCH_URL = "somelink"
    var match : [Matchs] = []
    var matchOdd : [MatchsOdds] = []


    @IBOutlet weak var totalMatchLabel: UILabel!

    @IBOutlet weak var totalOddsLabel: UILabel!

    fileprivate func getMatchData(url:String) {

        Alamofire.request(url).responseJSON {
            response in
                if response.result.isSuccess {
                    print("I got the match data")
                    let matchJSON : JSON = JSON(response.result.value!)
                    self.getMatch(json: matchJSON)

                }else {
                    print("Match Unavailable")
                }

          self.tableview.reloadData()
      }

    }


    fileprivate func getMatch(json: JSON) {

      if let matchs = json["data"]["b"]["f"]["list"].array {

        matchs.forEach { (arg0) in

          let events = arg0
          let tournamentName = events["tournamentName"].stringValue
          let homeTeam = events["homeTeam"].stringValue
          let mbs = events["mbs"].intValue
          let matchCode = events["matchCode"].intValue
          let matchTime : String = events["eventHour"].stringValue
          let awayTeam = events["awayTeam"].stringValue
          let matchTimeFirst5 = matchTime.prefix(5)

          let allMatch = Matchs(time: String(matchTimeFirst5), mbs: mbs, league: tournamentName, code: matchCode, homeTeam: homeTeam, awayTeam: awayTeam)


          let homeWin = events["oddList"][0]["v"].doubleValue
          let draw = events["oddList"][1]["v"].doubleValue
          let awaywin = events["oddList"][2]["v"].doubleValue
          let under = events["oddList"][3]["v"].doubleValue
          let over = events["oddList"][4]["v"].doubleValue



          let fiveOdds = MatchsOdds(homeWin: homeWin, awayWin: awaywin, draw: draw, under: under, over: over)
          match.append(allMatch)
          matchOdd.append(fiveOdds)

        }

    }

  }


    override func viewDidLoad() {
        super.viewDidLoad()

        getMatchData(url: MATCH_URL)
    }
    override func viewDidAppear(_ animated: Bool) {


        }

}
extension MainViewController: UITableViewDelegate,UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return match.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let matcCell = match[indexPath.row]

    let cell = tableView.dequeueReusableCell(withIdentifier: "oddsCell") as! OddsTableViewCell

    tableView.separatorStyle = .none
    cell.matchToMatch(matcs: matcCell)
    tableview.allowsSelection = false
    cell.collectionview.tag = indexPath.row
    cell.collectionview.reloadData()
    cell.matchOddCV = matchOdd
    return cell
  }
}

从这里没问题。我将数据写入Tableviewcell标签。但是当我尝试将MatchOdds数据添加到Collectionview单元格标签时。我只有第一个重复重复的数据:Minimized

这是Tableviewcell的代码:

class OddsTableViewCell: UITableViewCell {

    @IBOutlet weak var reloadButton: RoundedButton!
    @IBAction func reloadBottonPressed() {
        print("reloadDataPressed")

    }
    var matchOddCV : [MatchsOdds]!
    @IBOutlet weak var collectionview: UICollectionView!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var mbsLabel: UILabel! {
        didSet{
            mbsLabel.layer.cornerRadius = 5
            mbsLabel.layer.masksToBounds = true
        }
    }

    @IBOutlet weak var leageLabel: UILabel!

    @IBOutlet weak var matchCodeLabel: UILabel!
    @IBOutlet weak var homeVsAwayLabel: UILabel!



    override func awakeFromNib() {
        super.awakeFromNib()
        collectionview.dataSource = self
        collectionview.delegate = self

    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

    }

    func matchToMatch (matcs : Matchs) {
        timeLabel.text = matcs.matchTime
        mbsLabel.text = String(matcs.matchMbs)
        leageLabel.text = matcs.matchLeague
        matchCodeLabel.text = String(matcs.matchCode)
        homeVsAwayLabel.text = "\(matcs.matchHomeTeam) - \(matcs.matchAwayTeam)"
    }


}

extension OddsTableViewCell: UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.bounds.width/5, height: collectionView.bounds.height)
    }


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "oddsCollectionViewCell", for: indexPath) as! OddsCollectionViewCell

        let matchCell = matchOddCV[indexPath.row]

        if indexPath.row == 0 {
                  cell.matchResultLabel.text = matchCell.oddResult[0]
                  cell.matchOddsLabel.text = String(matchCell.homeWin)

                }else if indexPath.row == 1{
                  cell.matchResultLabel.text = matchCell.oddResult[1]
                  cell.matchOddsLabel.text = String(matchCell.draw)

                }else if indexPath.row == 2 {
                  cell.matchResultLabel.text = matchCell.oddResult[2]
                  cell.matchOddsLabel.text = String(matchCell.awayWin)

                }else if indexPath.row == 3 {
                  cell.matchResultLabel.text = matchCell.oddResult[3]
                  cell.matchOddsLabel.text = String(matchCell.under)

                }else if indexPath.row == 4 {
                  cell.matchResultLabel.text = matchCell.oddResult[4]
                  cell.matchOddsLabel.text = String(matchCell.over)

                }

        cell.matchOddsLabel.layer.borderWidth = 0.5
        cell.matchOddsLabel.layer.borderColor = UIColor.lightGray.cgColor
        cell.matchResultLabel.layer.borderWidth = 0.5
        cell.matchResultLabel.layer.borderColor = UIColor.lightGray.cgColor
        return cell
    }

}

Collectionviewcell代码:

class OddsCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var matchResultLabel: UILabel!
    @IBOutlet weak var matchOddsLabel: UILabel!
}

2 个答案:

答案 0 :(得分:1)

根据表的cellForRowAt

cell.collectionview.reloadData()
cell.matchOddCV = matchOdd

您为所有表单元格内的所有集合分配相同的数组,您需要在每个Matchs对象内创建一个array属性并执行

let matcCell = match[indexPath.row]
cell.matchOddCV = matcCell.odds // create odds array and assign data for each object
cell.collectionview.reloadData()

答案 1 :(得分:0)

如我所见,在设置新列表collectionview之前,您正在重新加载matchOddCV

所以您应该这样做:

// assign the new list
 cell.matchOddCV = matchOdd
// reload colllectionview
 cell.collectionview.reloadData()