[英]Implementing like and unlike functionality in Swift using Parse
我正在嘗試使用Swift 2.0,Storyboard和Parse在我的iOS應用中實現“喜歡/不喜歡”功能,用戶可以在其中喜歡/不喜歡其他用戶或他們自己創建的帖子-就像Instagram,Facebook和其他社交應用一樣。
我在情節提要中將一個按鈕連接到一個名為likeButton
的IBOutlet
和一個名為likeButtonTapped
的IBAction
。
我相信cellForRowAtIndexPath
方法也可以正確實現此功能。
我認為我對以下代碼的注釋中需要發生的事情有正確的想法,但是,我不知道如何檢查特定帖子是否被喜歡。 如何檢查帖子是否被喜歡,以便可以切換likeButton
圖像,遞增/遞減likeCount
以及添加/刪除當前用戶與該用戶喜歡的帖子之間的關系。
另外,我是否對標准的相似/不相似功能采用“正確”(傳統)方法? 我希望聽到您的反饋。 感謝您的時間和幫助!
class TimelineFeedViewController: PFQueryTableViewController {
var userLike = PFUser.currentUser()?.relationForKey("likes")
@IBAction func likeButtonTapped(sender: UIButton) {
// The following code has errors - for example, `object` is an unresolved
// identifier (it's supposed to be a PFObject that holds a post at a specific
// indexPath)
// Also, I cant access the likeButton for some reason. Only when I do
// cell.likeButton in `cellForRowAtIndexPath`.
// If the button is liked already (it's filled)
// Toggle likeButton image to UNfilled version
// "if likeButton isLiked == true" below is pseudocode of what I am trying to do
if likeButton isLiked == true {
let image = UIImage(named: "likeButtonUnfilled")
cell.likeButton.setImage (image, forState: UIControlState)
// Decrement the likeCount
object!.decrementKey("count")
// Remove the relation bet user and post
self.userLike?.removeObject(object!)
} else {
// the button is NOT liked already (it's not filled)
// toggle the image to the filled version
let image = UIImage(named: "likeButton")
cell.likeButton.setImage (image, forState: UIControlState)
// Increment the likeCount
object!.incrementKey("count")
// Add the relation bet. user and post
self.userLike?.addObject(object!)
}
object!.saveIngBackground()
PFUser.currentUser()?.saveInBackground()
self.tableView.reloadData()
}
}
假設您擁有自定義UITableViewCell類並已從Parse中獲取數據,而不是在UITableView數據源方法中
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("skillsCell", forIndexPath: indexPath) as! YOURTableViewCell
//Check If item is liked
if (isLiked) {
//Set image for like on button
}
else {
//Set image for unlike on button
}
cell.YourButton.tag = indexPath.row // This will assign tag to each button in tableView
return cell
}
比在YourViewController中添加UIButton動作
@IBAction func testButtonAction(sender: UIButton) {
print(sender.tag)
let cell = testTableView.cellForRowAtIndexPath(NSIndexPath(forRow: sender.tag, inSection: 0)) as! TestTableViewCell
if cell.likeButton.titleLabel?.text == "Cell \(sender.tag)" { //Your logic here. Check If button's image has "Liked Image than change Image to UnLiked Image"
cell.likeButton.text = "\(sender.tag)"
}
else {
cell.likeButton.text = "Cell \(sender.tag)"
}
}
這將實現UITableView中的按鈕的“贊/不喜歡”。 還要確保您相應地更新了Parse中的Class。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.