Swift:Watchkit Table 未填充

Swift: Watchkit Table not populating

这是我已经为 iPhone 制作的应用程序,我想将其用于 Apple Watch。

我有一个函数使用 SwiftyJSON 来解析 JSON 并收集我用来填充 table 的各种信息。在 willActiviate 中,我遍历所有行并为它们编制索引以获取我需要在标签上显示的信息。或者至少,这就是我想要做的。当我 运行 它时,显示了正确数量的标签,但标签不显示任何内容。我还创建了 loadTableData() 来手动重新加载 tableData。

如果我在尝试填充它时做错了什么,或者如果我做错了其他事情,我将不胜感激。

我的代码:

     @IBOutlet weak var earthTable: WKInterfaceTable!
    private func loadTableData() {
        getEarthquakeInfo { (info) in

            self.earthTable.setNumberOfRows(0, withRowType: "earthquake")
            self.earthTable.setNumberOfRows(info.count, withRowType: "earthquake")

        }

    }



    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)

            self.loadTableData()


    }

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()
        for index in 0..<self.earthTable.numberOfRows {
            var currentRow = self.earthTable.rowControllerAtIndex(index) as earthquakeViewController


            let time = info[self.earthTable.indexOfAccessibilityElement(currentRow)].time
            let mag = info[self.earthTable.indexOfAccessibilityElement((currentRow))].mag
            let title = info[self.earthTable.indexOfAccessibilityElement(currentRow)].title
            currentRow.titleLabel.setText("\(title)")
            currentRow.timeLabel.setText("\(time)")
            currentRow.magLabel.setText("\(mag)")




        }

            }
    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }

}

如果需要,我在其中解析 JSON 的整个函数:

class InterfaceController: WKInterfaceController {

        var info = [AppModel]()

        func getEarthquakeInfo(completion: (results : [AppModel]) ->Void ){


            DataManager.getEarthquakeDataFromFileWithSuccess {
                (data) -> Void in

                let json = JSON(data: data)


                if var JsonArray =  json.array {
                    JsonArray.removeAtIndex(0)

                    for appDict in JsonArray {
                        // parsing
                        var ids: String? = appDict["id"].stringValue
                        var title: String? = appDict["title"].stringValue
                        var time: String = appDict["time"].stringValue
                        var lattitude: String? = appDict["lat"].stringValue
                        var longitude: String? = appDict["lng"].stringValue
                        var north: String? = appDict["north"].stringValue
                        var west: String? =  appDict["west"].stringValue
                        var mag: String? = appDict["mag"].stringValue
                        var depth: String? = appDict["depth"].stringValue
                        var timeStamp: String? = appDict["timestamp"].stringValue

                        // Splitting up title string into 2 parts
                        let newString = title!.stringByReplacingOccurrencesOfString("  ", withString: " - ", options: NSStringCompareOptions.LiteralSearch, range: nil)
                        var title2strings = newString.componentsSeparatedByString(" - ")
                        var scale = title2strings[0]
                        var location = title2strings[1]

                        // replacing M in scale string with Richter Scale
                        let scaleString = scale.stringByReplacingOccurrencesOfString("ML", withString: "Magnitude", options: NSStringCompareOptions.LiteralSearch, range: nil)
                        let scaleString2 = scaleString.stringByReplacingOccurrencesOfString("mb", withString: "Magnitude", options: NSStringCompareOptions.LiteralSearch, range: nil)
                        let scaleString3 = scaleString2.stringByReplacingOccurrencesOfString("Mw", withString: "Magnitude", options: NSStringCompareOptions.LiteralSearch, range: nil)
                        let scaleString4 = scaleString3.stringByReplacingOccurrencesOfString("MD", withString: "Magnitude", options: NSStringCompareOptions.LiteralSearch, range: nil)
                        let scaleString5 = scaleString4.stringByReplacingOccurrencesOfString("M ", withString: "Magnitude ", options: NSStringCompareOptions.LiteralSearch, range: nil)

                        //Formatting the date
                        var date = NSDate(dateString: time).getDatePart()

                        // Collecting all the information
                        var information = AppModel(idEarth: ids, title: title, time: date, lat: lattitude, lng: longitude, north: north!, west: west, mag: mag, depth: depth, timeStamp: timeStamp, location: location, scale: scaleString5)
                        self.info.append(information)

                        //sorting array by highest magnitude
                        // self.info.sort({[=13=].mag > .mag})


                        // returning the completion handler
                        completion(results: self.info)
                    }


                }

            }

        }

我使用的 AppModel 文件(如果需要):

import Foundation
import WatchKit
class AppModel: NSObject, Printable {
    let idEarth: String
    let title: String
    let time: String
    let lat: String
    let lng: String
    let north: String
    let west: String
    let mag: String
    let depth: String
    let timeStamp: String
    let scale: String
    let location: String

    override var description: String {
        return "ID: \(idEarth), TITLE: \(title), TIME: \(time), LAT: \(lat), LNG: \(lng), NORTH: \(north), WEST: \(west), MAG: \(mag), DEPTH: \(depth), TIMESTAMP: \(timeStamp), LOCATION: \(location), SCALE: \(scale) \n"
    }

    init(idEarth: String?, title: String?, time: String?, lat: String?, lng: String?, north: String, west: String?, mag: String?, depth: String?, timeStamp: String?, location: String?, scale: String?) {
        self.idEarth = idEarth ?? ""
        self.title = title ?? ""
        self.time = time ?? ""
        self.lat = lat ?? ""
        self.lng = lng ?? ""
        self.north = north ?? ""
        self.west = west ?? ""
        self.mag = mag ?? ""
        self.depth = depth ?? ""
        self.timeStamp = timeStamp ?? ""
        self.location = location ?? ""
        self.scale = scale ?? ""

    }

}

我认为你的问题是你试图在 willActivate 中填充你的 tableView 但你甚至不确定你是否已经拥有数据(可能无法到达来自 getEarthquakeInfo 的完成处理程序)。

您应该在设置行数后尝试设置单元格。 顺便问一下,为什么要设置两倍的数字或行数?

尝试这样的事情

@IBOutlet weak var earthTable: WKInterfaceTable!
    private func loadTableData() {
        getEarthquakeInfo { (info) in

            self.earthTable.setNumberOfRows(info.count, withRowType: "earthquake")

            //Create cells
            for index in 0..<self.earthTable.numberOfRows {
                var currentRow = self.earthTable.rowControllerAtIndex(index) as earthquakeViewController


                let time = info[self.earthTable.indexOfAccessibilityElement(currentRow)].time
                let mag = info[self.earthTable.indexOfAccessibilityElement((currentRow))].mag
                let title = info[self.earthTable.indexOfAccessibilityElement(currentRow)].title
                currentRow.titleLabel.setText("\(title)")
                currentRow.timeLabel.setText("\(time)")
                currentRow.magLabel.setText("\(mag)")
            }

        }

    }



    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)

        self.loadTableData()

    }

    override func willActivate() {
        // This method is called when watch view controller is about to be visible to user
        super.willActivate()


    }
    override func didDeactivate() {
        // This method is called when watch view controller is no longer visible
        super.didDeactivate()
    }

}