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

Posted

技术标签:

【中文标题】JSON中的值不显示在tableviewcell自定义中【英文标题】:Value in JSON does not display in tableviewcell custom 【发布时间】:2016-09-15 16:59:08 【问题描述】:

无法在 TableViewCell 中显示数据。数据报告事件,但是当您打开数组“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

    

她是控制器。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.

【问题讨论】:

是的。为什么我做错了什么?我在成为自我大小的 RayWenderlinch 的课程中​​做错了。可以帮助纠正错误吗? 您在SportDetailViewController 中的哪里加载了您的事件数据? 我已经加载了数据事件的另一个控制器。我已经显示了数据“事件”。 【参考方案1】:

从您的struct 中删除这个init:(因为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()
    
    ...
    ...

这应该可以解决您的问题。

【讨论】:

查看我的编辑并从此处删除staticstatic func eventsFromBundle () 只删除static 关键字,而不是整行。 好的,你删除了init()这个方法吗?您是否将var events = Event.eventsFromBundle () 更改为var events = [Event]()?您是否在SportViewController 类的viewDidLoad() 方法中添加了events = Event().eventsFromBundle()?? 让我们做一件事。您将项目上传到某处并提供链接。您可能在其他地方遇到问题。 好的,我会告诉你的。现在我正在安装 Xcode :(

以上是关于JSON中的值不显示在tableviewcell自定义中的主要内容,如果未能解决你的问题,请参考以下文章

如何从自定义 tableviewcell 中的按钮显示弹出视图?

如何在特定 indexpath.row 上显示自定义 tableviewcell

使用 JSON 序列化从 Twitter 填充自定义 TableViewCell

iOS 自定义 TableViewCell 行高(嵌套 FlowLayout)

如何在 TableviewCell 中显示 Json 数据?

iOS 7 中自定义 TableViewCell 中的自动布局问题