IBAction更新tableviewcontroller中的每个单元格行

时间:2015-11-02 14:19:33

标签: ios iphone swift uitableview tableview

我有一个表格视图单元格和UITableViewController。我在表格视图单元格中有两个 IBOutlets (喜欢/不喜欢)。我在TableViewController中也有两个 IBActions 。单击 IBActions 时,它会更新表视图中的每个单元格。这是我的代码:

表视图控制器:

class UserFeedTableViewController: PFQueryTableViewController {
var shouldReloadOnAppear: Bool = true

// Votes: -1 for dislike, 1 for like, 0 for no vote
var vote: Int = 0 // initialize to user's existing vote, retrieved from the server
var likeCount: Int = 0 // initialize to existing like count, retrieved from the server
var dislikeCount: Int = 0 // initialize to existing dislike count, retrieved from the server

@IBAction func dislikeButton(sender: UIButton) {

buttonWasClickedForVote(-1)

self.tableView.reloadData()
print(likeCount)
print(dislikeCount)

}

@IBAction func likeButton(sender: UIButton) {

buttonWasClickedForVote(1)

self.tableView.reloadData()
print(likeCount)
print(dislikeCount)      

}

private func buttonWasClickedForVote(buttonVote: Int) {
if buttonVote == vote {
    // User wants to undo her existing vote.
    applyChange(-1, toCountForVote: vote)
    vote = 0
}

else {
    // User wants to force vote to toggledVote.
    // Undo current vote, if any.
    applyChange(-1, toCountForVote: vote)

    // Apply new vote.
    vote = buttonVote
    applyChange(1, toCountForVote: vote)
}

}

private func applyChange(change: Int, toCountForVote vote: Int ) {
if vote == -1 { dislikeCount += change }
else if vote == 1 { likeCount += change }

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
let CellIdentifier = "Cell"

    var cell: UserFeedCell? = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as? UserFeedCell

    if cell == nil {
        cell = UserFeedCell(style: UITableViewCellStyle.Default, reuseIdentifier: CellIdentifier)

    }

    if object != nil {
        cell!.likeButton.selected = vote == 1

        cell!.dislikeButton.selected = vote == -1
        cell!.likeButton.setTitle("\(likeCount)", forState: .Normal)
        cell!.dislikeButton.setTitle("\(dislikeCount)", forState: .Normal)

    }

return cell
}

表视图单元格:

class UserFeedCell: PFTableViewCell {

@IBOutlet weak var likeButton: UIButton!

@IBOutlet weak var dislikeButton: UIButton!

var post: PFObject? {
 didSet{   
  }

} }

0 个答案:

没有答案