JSON中的值不会显示在tableviewcell自定义中

时间:2016-09-15 16:59:09

标签: ios json uitableview swift3

无法在TableViewCell.Data中显示事件报告中的数据,但是当您打开数组“sports”时,以cels为单位显示数据。显示标题显示并且传输结束...

这是我的json代码......

Event.swift


    import UIKit

    struct Event {
        let match : String
        let forecast : String
        let data : String
        let image : UIImage
        var sports : [Sport]

        init (match : String, forecast : String, data: String, image : UIImage, sports : [Sport]) {

        self.match = match
        self.forecast = forecast
        self.data = data
        self.image = image
        self.sports = sports


      }

        static func eventsFromBundle ()-> [Event] {

            var events = [Event] ()


            guard let url = Bundle.main.url(forResource: "events", withExtension: "json") else {
                return events
            }
                do {
                    let data = try Data(contentsOf: url)
                    guard let rootObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String : Any]  else {

                        return events
                    }

                    guard let eventObjects = rootObject["events"] as? [[String: AnyObject]] else {
                        return events
                    }
                    for eventObject in eventObjects {
                        if let match = eventObject["match"] as? String,
                            let forecast = eventObject["forecast"]  as? String,
                            let data = eventObject["data"] as? String,
                            let imageName = eventObject["image"] as? String,
                            let image = UIImage(named: imageName),
                            let sportsObject = eventObject["sports"] as? [[String : String]]{
                            var sports = [Sport]()
                            for sportObject in sportsObject {
                              if let  nameTitle = sportObject["name"] ,
                                    let titleName = sportObject["image"],
                                    let titleImage = UIImage(named: titleName + ".jpg"),
                                    let prognozLabel = sportObject["prognoz"],
                                    let obzor = sportObject["obzor"] {
                                sports.append(Sport(name: nameTitle, prognoz: prognozLabel, image: titleImage, obzor: obzor, isExpanded: false))

                                }
                            }

                            let event = Event(match: match, forecast: forecast, data: data, image: image, sports: sports)
                            events.append(event)

                        }
                    }


                } catch {
                    return events
            }

            return events
        }

    }

import UIKit

class SportViewController: BaseViewController {

    var events = Event.eventsFromBundle ()


    @IBOutlet weak var tableView: UITableView!


    override func viewDidLoad() {
        super.viewDidLoad()
        addSlideMenuButton()
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 100


    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        NotificationCenter.default.addObserver(forName: .UIContentSizeCategoryDidChange, object: .none, queue: OperationQueue.main) { [weak self] _ in
           self?.tableView.reloadData()

        }
    }


        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? SportDetailViewController,
            let indexPath = tableView.indexPathForSelectedRow {
            destination.selectedEvent = events[indexPath.row]
        }
    }
}



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


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellMatch", for: indexPath) as! SportTableViewCell

    let event = events[indexPath.row]
    cell.matchLabel.text = event.match
    cell.imageMatch.image = event.image
    cell.forecastLabel.text = event.forecast
    cell.dataLabel.text = event.data

    cell.matchLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
    cell.forecastLabel.font = UIFont.preferredFont(forTextStyle: .callout)
    return cell

    }
}

她是controller.SportDetailViewController.swift

import UIKit

class SportDetailViewController: UIViewController {

    var selectedEvent : Event!



    let obzorText = "Select for more info >"

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        title = selectedEvent.match
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 300



        // Do any additional setup after loading the view.
           }
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)


            }

    }



 extension SportDetailViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
     {
        return selectedEvent.sports.count

    }



 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell : SportDetailTableViewCell = tableView.dequeueReusableCell(withIdentifier: "cellMatch", for: indexPath) as! SportDetailTableViewCell

            let sport = selectedEvent.sports[indexPath.row]


            cell.nameTitle.text = sport.name
            cell.titleImage.image = sport.image
            cell.prognozLabel.text = sport.prognoz
            cell.selectionStyle = .none
            cell.nameTitle.backgroundColor = UIColor.darkGray
            cell.backgroundColor = UIColor.red

            cell.obzorText.text = sport.isExpanded ? sport.obzor : obzorText
            cell.obzorText.textAlignment = sport.isExpanded ? .left : .center

            return cell
}
   }



 extension SportDetailViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    guard let cell = tableView.cellForRow(at: indexPath) as? SportDetailTableViewCell else { return }

        var sport = selectedEvent.sports[indexPath.row]

        sport.isExpanded = !sport.isExpanded
        selectedEvent.sports[indexPath.row] = sport

        cell.obzorText.text = sport.isExpanded ? sport.obzor : obzorText
        cell.obzorText.textAlignment = sport.isExpanded ? .left : .center


        tableView.beginUpdates()
        tableView.endUpdates()

        tableView.scrollToRow(at: indexPath, at: .top, animated: true)

    }

}

所有这些方法都尝试过:tableview.datasource = self,tableview.delegate =selfиreloadData()..... in viewDidLoad。

1 个答案:

答案 0 :(得分:0)

init中删除此struct :(因为struct获得免费初始化程序)

init (match : String, forecast : String, data: String, image : UIImage, sports : [Sport]) {

    self.match = match
    self.forecast = forecast
    self.data = data
    self.image = image
    self.sports = sports
}

现在,由于您在类范围内调用方法,因此不会填充var events。所以改变这个:

class SportViewController: BaseViewController {

    var events = Event.eventsFromBundle ()
    ...
    ...
}

class SportViewController: BaseViewController {

    var events = [Event]()
    ...
    ...
    override func viewDidLoad() {
        super.viewDidLoad()
        addSlideMenuButton()
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 100

        events = Event().eventsFromBundle()
    }
    ...
    ...
}

这可以解决您的问题。