像按钮功能没有通过解析

时间:2015-11-01 22:20:47

标签: ios swift parse-platform pfquery

我正在尝试通过解析在我的应用上实现类似于facebook或Instagram的类似按钮功能。我尝试使用下面的代码,它的工作原理。当用户点击对象上的按钮(或者在我的情况下消息)时,类似物上升1点。但是,当用户退出应用程序并启动它时,他们可以再次喜欢同一个对象,这意味着他们可以根据需要多次使用。我是否需要在此代码中编辑某些内容或尝试使用完全不同的方法?

@IBAction func likeButton(sender: UIButton) {
    sender.enabled = false
    sender.userInteractionEnabled = false
    sender.alpha = 0.5

    //get the point in the table view that corresponds to the button that was pressed
    //in my case these were a bunch of cells each with their own like button
    let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
    let hitIndex = self.tableView.indexPathForRowAtPoint(hitPoint)
    let object = objectAtIndexPath(hitIndex)

    //this is where I incremented the key for the object
    object!.incrementKey("count")
    object!.saveInBackground()

    self.tableView.reloadData()
    NSLog("Top Index Path \(hitIndex?.row)")
}

1 个答案:

答案 0 :(得分:0)

以下是解决问题的方法:

首先,我会将按钮禁用为自己的功能,如下所示:

func disableButton(button: UIButton){
    button.enabled = false
    button.userInteractionEnabled = false
    button.alpha = 0.5
}

(当用户按下相似按钮时,它会被禁用,如下所示:)

@IBAction func likeButton(sender: UIButton) {
    disableButton(sender)

    //get the point in the table view that corresponds to the button that was pressed
    //in my case these were a bunch of cells each with their own like button
    let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
    let hitIndex = self.tableView.indexPathForRowAtPoint(hitPoint)
    let object = objectAtIndexPath(hitIndex)

    //this is where I incremented the key for the object
    object!.incrementKey("count")
    object!.saveInBackground()

    self.tableView.reloadData()
    NSLog("Top Index Path \(hitIndex?.row)")
}

然后我会为用户创建他们喜欢的帖子的属性,这些帖子是objectIds这些帖子的字符串数组。 (由于用户可能最终喜欢很多帖子,你真的应该使用关系,但是数组更容易理解。PFObjects之间的关系文档是here。)然后,当为每个帖子创建单元格时发布,cell是您要创建的单元格,post是列表中的当前帖子,cell.likeButton是来自单元格的类似按钮:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    let cell = YourCell()
    let post = posts[indexPath.row]
    if (PFUser.currentUser!["likedPosts"] as! [String]).contains(post.objectId){
        cell.disableButton(cell.likeButton)
    }
    //Setup rest of cell