如何用解析字典填充tableView?

时间:2016-04-13 16:08:50

标签: swift uitableview parse-platform

我正在尝试使用解析字典(包含字符串和位置)填充tableView,我正在设法上传数据以进行解析并将其下载到控制台,但是我在添加它时遇到了很多麻烦我的tableView,地方就像这样添加(在地图视图中):

let geoPoint = PFObject(className: "location")

geoPoint["location"] = activePlace
geoPoint["spot"] = places
geoPoint.saveInBackgroundWithBlock { (succes, error) -> Void in
    print("place has been saved")
}

并将其下载/添加到控制台,如下所示:

let query = PFQuery(className: "location")
query.findObjectsInBackgroundWithBlock { (object, error) in


    if error != nil {

        print(error)

    }else {

        print(object)
        self.tableView.reloadData()

    }
}

我的tableView的完整代码是:

import UIKit
import Parse

var rideSpots = [""]

//test start

//class Place {
//    var ACL : String
//    var location : String

 //   init(ACL : String, location : String) {
 //       self.ACL = ACL
 //       self.location = location
 //   }
//}
//let places2 : [Place] = []
//test stop

var places = [Dictionary<String,String>()]

var activePlace = -1

class TableViewController: UITableViewController {

    @available(iOS 8.0, *)
    func companyNameUpdatedAlert(title: String, error: String, indexPath: Int) {

        let alert = UIAlertController(title: title, message: error, preferredStyle: UIAlertControllerStyle.Alert)

        alert.addTextFieldWithConfigurationHandler { (textField) -> Void in

            textField.placeholder = "Enter new text"

        }

        alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in

            let lat = places[indexPath]["lat"]!

            let lon = places[indexPath]["lon"]!

            places.removeAtIndex(indexPath)

            places.insert(["name" : alert.textFields![0].text!, "lat" : lat, "lon" : lon], atIndex: indexPath)

            self.tableView.reloadData()

            NSUserDefaults.standardUserDefaults().setObject(places, forKey: "places")
            NSUserDefaults.standardUserDefaults().synchronize()


        }))

        self.presentViewController(alert, animated: true, completion: nil)


    }

    @available(iOS 8.0, *)
    override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {

        let changeText = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Change spot name" , handler: { (action:UITableViewRowAction, indexPath:NSIndexPath) -> Void in

            self.companyNameUpdatedAlert("Update text", error: "enter text below", indexPath: indexPath.row)

        })
     /*
        let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete" , handler: { (action:UITableViewRowAction, indexPath:NSIndexPath) -> Void in

            places.removeAtIndex(indexPath.row)

            tableView.reloadData()

            NSUserDefaults.standardUserDefaults().setObject(places, forKey: "places")
            NSUserDefaults.standardUserDefaults().synchronize()

        })
        */
        return [changeText]


    }

    override func viewDidLoad() {



            super.viewDidLoad()

        //retreve the data from parse start

        let query = PFQuery(className: "location")
        query.findObjectsInBackgroundWithBlock { (object, error) in


            if error != nil {

                print(error)

            }else {

                print(object)
                self.tableView.reloadData()

            }
        }


               //retreve the data from parse stop


            if places.count == 1 {

                places.removeAtIndex(0)

                places.append(["name":"GO to map to add spot","lat":"90","lon":"90"])




            }
            if NSUserDefaults.standardUserDefaults().objectForKey("places") != nil {

                places = NSUserDefaults.standardUserDefaults().objectForKey("places") as! [Dictionary]


            }

        }


    override func didReceiveMemoryWarning() {

        didReceiveMemoryWarning()

    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

        return 1

    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return places.count
        //return places2.count


    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

        cell.textLabel?.text = places[indexPath.row]["name"]
        //cell.textLabel!.text = places2[indexPath.row].location


        return cell



    }

    override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {

        activePlace = indexPath.row

        return indexPath

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "newPlace" {

            activePlace = -1


        }

    }

    override func viewWillAppear(animated: Bool) {

    tableView.reloadData()


    }

}

这听起来很容易,但出于某些原因我无法弄明白,所以任何帮助都会受到高度赞赏。

谢谢!

1 个答案:

答案 0 :(得分:0)

由于您正在尝试创建一个对象来表示较大的PFObject的较小部分,我建议您创建一个地方结构

struct Places {
    var someData: String!
    var someMoreData: String!
}

//Class level variable of places
var places: [Places]?

然后,当您从查询中收到对象时,您可以创建您的位置并将其附加到数组中。

var placeToAdd = Places(someData: object["name"], someMoreData: object["anotherField"])
places.append(placeToAdd)

最后,在创建单元格时,您可以适当地访问信息。

cell.textLabel!.text = places[indexPath.row].name