Voting buttons with Parse in Swift

2019-09-01 05:02发布

问题:

A quick overview of what I'm trying to make. I'm making an app to show my film reviews. I have a PFQueryTableviewController of which I use a custom cell. This table shows films which come from my Parse database. In each cell, there a 3 UIButtons, of which I want the user to use to vote for the film (happyVote, OkVote, sadVote). Over the top of each button is a UILabel that simply displays a count.

How I want it to work

  1. When a user presses one of the buttons, the vote increases by 1.
  2. When a user presses the same button again, the vote decreases by 1. Or,
  3. If the user had pressed a different button, the vote decreases on the first button and increases on the button just pressed.
  4. The user can only ever vote on one of the buttons.
  5. The vote is shown by the UILabel showing the count, and by the button image changing.

See below for a visual:

This is what I've added in Parse:

So far, I've added the code to increase the vote count in Parse, in my TableViewController.swift:

@IBAction func upVoteButton(sender: AnyObject) {

    let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
    let hitIndex = self.tableView.indexPathForRowAtPoint(hitPoint)

    let object = objectAtIndexPath(hitIndex)
    object!.incrementKey("UpVoteCount")
    object!.saveInBackground()
    self.tableView.reloadData()

}

This kind of works, except, the user can keep increasing the count, and they can vote on all 3 buttons. And it doesn't change the Button Image when pressed.

In my cellForRowAtIndexPath method, I've put:

 let downVote = object!.valueForKey("DownVoteCount") as! Int
    cell.downVoteLabel.text = "\(downVote)"
    let middleVote = object!.valueForKey("MiddleVoteCount") as! Int
    cell.middleVoteLabel.text = "\(middleVote)"
    let upVote = object!.valueForKey("UpVoteCount") as! Int
    cell.upVoteLabel.text = "\(upVote)"

I have searched for a while for some examples of how to figure the rest out, but can't find anything, and I'm really struggling to figure the next steps out.

Any help will be greatly appreciated, and please let me know if you need/want to see anymore of my code. Thanks

回答1:

In your upVoteButton() method, you can add the other two buttons and set them button.enabled = false inside an if statement like:

if downVoteButton.enabled == true {
    downVoteButton.enabled = false
} else if downVoteButton.enabled == false {
    downVoteButton.enabled = True
}

And do the same with the middleVoteButton in antoher if statement or the same, whatever floats your boat, also within the other button methods with the appropriate buttons. This helps disables the buttons when pressed and then enables it when it's pressed again.

And for the image changing you can follow this.