ios - 点赞按钮功能无法通过解析工作

标签 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)")
}

最佳答案

这是我解决问题的方法:

首先,我会将禁用按钮放入其自己的函数中,如下所示:

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

关于ios - 点赞按钮功能无法通过解析工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33467884/

相关文章:

ios - 如何让我的 iphone/ios 应用程序在启动时打开一个 Safari 窗口

iphone - 我需要一些关于@2x UIImageViews 的信息

ios - 带有完成 block 的 NSOperation

swift - 绘制没有对角线的 SCNBox 边缘?

swift - 仅当键盘处于事件状态时,点击背景才能关闭 TextField 键盘

android - 当我将解析代码放入其中时,应用程序崩溃了

ios - 在 iOS 中将图像大小减小至最大 100 kb,并固定尺寸 512x512

ios - 显示用户名 - 解析

swift - 不更新帖子 Parse Swift

随着时间的推移,swift spritekit 会增加节点创建的频率