使用UITableView从Swift中的Parse.com检索,变异和保存数组的教程

问题描述 投票:2回答:1
import UIKit

class FeedTableViewController: UITableViewController {
var navBar:UINavigationBar=UINavigationBar()
let font = UIFont(name: "Baskerville", size: 15)

var feedData:NSMutableArray = NSMutableArray()



required init(coder aDecoder: NSCoder){
    super.init(coder: aDecoder)
}




@IBAction func likeButton(sender: AnyObject) {
    if var votes:Int? = quote!.objectForKey("votes") as? Int {
        votes!++
    }

}

@IBAction func loadData(sender: AnyObject?) {
    feedData.removeAllObjects()

    var findFeedData:PFQuery = PFQuery(className: "userQuotes")

    findFeedData.findObjectsInBackgroundWithBlock{
        (objects:[AnyObject]?, error:NSError?)->Void in

        if error == nil{
            if let objs = objects{
                for object in objs{
                    let quote:PFObject = object as! PFObject
                    self.feedData.addObject(quote)
                   // let user:PFUser = (object as! NSArray).lastObject as! PFUser



                }
                //println(self.feedData)

                let array:NSArray = self.feedData.reverseObjectEnumerator().allObjects
                self.feedData = NSMutableArray(array: array)

                NSOperationQueue.mainQueue().addOperationWithBlock({
                    self.tableView.reloadData()
                })
            }
        }

    }

}



override func viewDidAppear(animated: Bool) {

    self.loadData( nil )


}


override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Quotezilla"

    // 3
    //self.navigationItem.setRightBarButtonItem(rightSearchBarButtonItem, animated: true)

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return feedData.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell:QuoteTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! QuoteTableViewCell

     let quote:PFObject = self.feedData.objectAtIndex(indexPath.row) as! PFObject

    cell.contentTextView!.font = font
    cell.timeStampLabel!.font = font
    cell.publisherLabel!.font = font

    cell.contentTextView.alpha = 0
    cell.timeStampLabel.alpha = 0
    cell.publisherLabel.alpha = 0

    cell.contentTextView.text = quote.objectForKey("content") as! String
    //cell.publisherLabel.text = quote.objectForKey("publisher") as? String

  /*  func loadLikes(){
        if var votes:Int? = quote.objectForKey("votes") as? Int {
            votes!++
        }
    }*/



    var dateFormatter:NSDateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "EEEE, MMM d, h:mm a"
    cell.timeStampLabel.text = dateFormatter.stringFromDate(quote.createdAt!)

    var votes:Int? = quote["votes"] as? Int
    if votes == nil {
        votes = 0
    }


    cell.likesLabel?.text = "\(votes!)"


    var myObject = quote["publisher"] as? PFObject
    myObject?.fetchIfNeeded()

    if let foundUser = myObject as? PFUser{
        cell.publisherLabel.text = foundUser.username
        UIView.animateWithDuration(0.7, animations: {

            cell.contentTextView.alpha = 1
            cell.timeStampLabel.alpha = 1
            cell.publisherLabel.alpha = 1

        })
    }

        return cell
}

所以我基本上尝试做的是创建一个喜欢或投票按钮。正如你在代码中看到的那样,我有一个likeButton动作,应该在parse中自动增加likes部分。我在cellForRowAtIndexPath函数中显示我已经填充到Parse本身的行中的当前喜欢。问题是我不能调用quote.objectForKey("votes"),因为我稍后会初始化它。我一直在研究这个问题,并且找不到通过likeButton动作解析投票的方法。

swift parse-platform tableview
1个回答
1
投票

你必须与网络生活在一起。这意味着当应用程序启动时,您的表将无法获得某些数据。正常处理特定单元格中缺少的对象或缺少键,只需使用某种占位符值。执行解析回调时,您已经正确强制刷新。

好的,所以大编辑

这堂课需要做很多工作。我甚至不会在这里详细说明每一个变化,但它基本上是一个完整的Parse.com教程。

这段代码编译得很干净,但我不能确定你的上下文中的所有内容。特别是在每个表行上都有'likesButton'作为自定义表格单元格视图的一部分吗?我在假设。

class FeedTableViewController: UITableViewController {
    var navBar = UINavigationBar()
    let font = UIFont(name: "Baskerville", size: 15)
    var feedData = [PFObject]()
    static let cellID = "cell"

    // NOTE! See how this tag is set below
    @IBAction func likeButton(sender: UIButton) {
        let quote = feedData[sender.tag]
        if let votes = quote.objectForKey("votes") as? Int {
            quote.setObject(votes + 1, forKey: "votes")
        }
        else {
            // CHALLENGE FOR YOU: handle the case of no votes attribute
        }
        // UPDATE the local UI
        tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: sender.tag, inSection: 0)],
                withRowAnimation: .None)
        // CHALLENGE FOR YOU: UPDATE Parse...start a new question if necessary
    }

    @IBAction func loadData(sender: AnyObject?) {
        feedData.removeAll()
        PFQuery(className: "userQuotes").findObjectsInBackgroundWithBlock {
            [unowned self]
            (objects: [AnyObject]?, error: NSError?) -> Void in
            if let objs = objects {
                for object in objs {
                    self.feedData.append(object as! PFObject)
                }
                self.feedData = self.feedData.reverse()
            }
            NSOperationQueue.mainQueue().addOperationWithBlock { self.tableView.reloadData() }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.loadData(nil)
        self.title = "Quotezilla"
    }

    // MARK: - Table view data source
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return feedData.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(FeedTableViewController.cellID, forIndexPath: indexPath) as! QuoteTableViewCell
        cell.likesButton!.tag = indexPath.row // See how tag works with the above
        cell.contentTextView!.font = font
        cell.timeStampLabel!.font = font
        cell.publisherLabel!.font = font

        cell.contentTextView.alpha = 0.0
        cell.timeStampLabel.alpha = 0.0
        cell.publisherLabel.alpha = 0.0

        let q = feedData[indexPath.row]
        if let content = q.objectForKey("content") as? String {
            cell.contentTextView.text = content
        }
        else {
            cell.contentTextView.text = "Content not found!"
        }
        var dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "EEEE, MMM d, h:mm a"
        cell.timeStampLabel.text = dateFormatter.stringFromDate(q.createdAt!)

        let votes = (q.objectForKey("votes") as? Int) ?? 0
        cell.likesLabel?.text = "\(votes)"
        let myObject = q.objectForKey("publisher") as? PFObject
        myObject?.fetchInBackgroundWithBlock {
            [unowned self]
            (object: PFObject?, error: NSError?) in
            NSOperationQueue.mainQueue().addOperationWithBlock {
                if let foundUser = object as? PFUser {
                    cell.publisherLabel.text = foundUser.username
                    UIView.animateWithDuration(0.7) {
                        cell.contentTextView.alpha = 1.0
                        cell.timeStampLabel.alpha = 1.0
                        cell.publisherLabel.alpha = 1.0
                    }
                }
                else {
                    cell.publisherLabel.text = "Publisher not found!"
                }
            }
        }
        return cell
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.