我将如何制作一个喜欢的按钮?

How would I make a like button?

我正在使用 Swift 中的练习教程制作社交媒体应用程序克隆,但我想使用 Parse 添加一个赞按钮,但不确定如何添加。有谁知道教程,或者您知道如何去做吗?我试图做一个这样的,但我很确定它不正确......

我把它放在单元格视图控制器中

@IBAction func likeButton(sender: AnyObject) {

    a++

    var post = PFObject(className: "Post")

    post["likes"] = a


}

}

这进入了提要视图控制器...

var messages = [String]()
var usernames  = [String]()
var imageFiles = [PFFile]()
var users = [String: String]()
var likesArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()

    var query = PFUser.query()

    query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

        if let users = objects {

            self.messages.removeAll(keepCapacity: true)
            self.users.removeAll(keepCapacity: true)
            self.imageFiles.removeAll(keepCapacity: true)
            self.usernames.removeAll(keepCapacity: true)
            self.likesArray.removeAll(keepCapacity: true)

            for object in users {

                if let user = object as? PFUser {

                    self.users[user.objectId!] = user.username!
                }

            }
        }
    })

    var getFollowedUsersQuery = PFQuery(className: "followers")

    getFollowedUsersQuery.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)

    getFollowedUsersQuery.findObjectsInBackgroundWithBlock { (objects, error) -> Void in

        if let objects = objects {

            for object in objects {

                var followedUser = object["following"] as! String

                var query = PFQuery(className: "Post")

                query.whereKey("userId", equalTo: followedUser)

                query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

                    if let objects = objects {

                        for object in objects {

                            self.messages.append(object["message"] as! String)

                            self.imageFiles.append(object["imageFile"] as! PFFile)

                            self.usernames.append(self.users[object["userId"] as! String]!)

                            self.likesArray.append(object["likes"] as? String)

                            self.tableView.reloadData()


                        }

                    }

                })

            }
        }
    }
}

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


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 usernames.count
}


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

    imageFiles[indexPath.row].getDataInBackgroundWithBlock { (data, error) -> Void in

        if let downloadedImage = UIImage(data: data!) {

            myCell.postedImage.image = downloadedImage
        }

    }


    myCell.username.text = usernames[indexPath.row]

    myCell.message.text = messages[indexPath.row]

    myCell.likeLabel.text = likesArray[indexPath.row]

    myCell.selectionStyle = .None

    return myCell
}


}

当您 post 图片和消息时,这是视图控制器...

var likes = 0

var picSelected = false

@IBOutlet var feed: UIButton!

func displayAlert(title: String, message: String) {

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

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


    }))

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

}


var activityIndicator = UIActivityIndicatorView()

@IBOutlet var imageToPost: UIImageView!

@IBAction func chooseImage(sender: AnyObject) {

    var image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    image.allowsEditing = false

   presentViewController(image, animated: true, completion: nil)

}

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {

    dismissViewControllerAnimated(true, completion: nil)

    imageToPost.image = image

    picSelected = true
}

@IBOutlet var message: UITextField!


@IBAction func postImage(sender: AnyObject) {

    if message.text != "" && picSelected != false  {
    picSelected = false
    activityIndicator = UIActivityIndicatorView(frame: view.frame)
    activityIndicator.backgroundColor = UIColor(white: 1.0, alpha: 0.5)
    activityIndicator.center = self.view.center
    activityIndicator.hidesWhenStopped = true
    activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
    view.addSubview(activityIndicator)
    activityIndicator.startAnimating()

    UIApplication.sharedApplication().beginIgnoringInteractionEvents()

    var post = PFObject(className: "Post")

    post["message"] = message.text

    post["userId"] = PFUser.currentUser()?.objectId!

    let imageData = UIImagePNGRepresentation(imageToPost.image)

    let imageFile = PFFile(name: "image.png", data: imageData)

    post["imageFile"] = imageFile

    post["likes"] = a

    post.saveInBackgroundWithBlock { (success, error) -> Void in

        self.activityIndicator.stopAnimating()
        UIApplication.sharedApplication().endIgnoringInteractionEvents()

        if error == nil {

            self.displayAlert("Image Posted!", message: "Your image has been posted successfully.")

            self.imageToPost.image = UIImage(named: "Blank-Person1.png")

            self.message.text = ""

        }

    }

    } else {
        displayAlert("Could Not Post Image!", message: "Please enter a message and/or select a picture.")
    }

}
override func viewDidLoad() {
    super.viewDidLoad()

}

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


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

我要制作这样的“赞”按钮:

  • 在解析中创建姓名列(数组列)以保存点击赞按钮的姓名
  • 在解析中创建 Likes 列(整数列)以保存 Names 列的计数

当有人点击赞按钮时,将他的名字添加到解析中的名称数组中,如果他再次点击它,则删除他的名字

并且您需要获取 NamesArray 列中的所有名称并在 swift 中对它们进行计数,然后更新 likes 列

我不确定,但我现在就是这么想的,但如果你想到它,你会找到更好的方法。