如何调用没有参数的函数来更新接口?

时间:2015-10-29 03:35:04

标签: ios swift

我想用我的模型更新我的界面。我在PFTableViewCell中有这两个出口:

class UserFeedCell: PFTableViewCell {

    @IBOutlet weak var likeButton: UIButton!
    @IBOutlet weak var dislikeButton: UIButton!

我想使用以下代码更新这两个插座按钮:

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)
    print(likeCount)
    print(dislikeCount)
}

@IBAction func likeButton(sender: UIButton) {
    buttonWasClickedForVote(1)
    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 }
}

private func updateUserInterfaceFromModel() {
    let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as! UserFeedCell
    cell.likeButton.selected = vote == 1
    cell.dislikeButton.selected = vote == -1
    cell.likeButton.setTitle("\(likeCount)", forState: .Normal)
    cell.dislikeButton.setTitle("\(dislikeCount)", forState: .Normal)
}

如何更新我的商店?我尝试拨打viewDidLoad,但我的网点没有更新。

2 个答案:

答案 0 :(得分:1)

您可以这样使用: -

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellIdentifier = "TableViewCell" // your cell identifier name in storyboard 
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! PFTableViewCell
    cell.likeButton.selected = vote == 1
    cell.dislikeButton.selected = vote == -1
    cell.likeButton.titleLabel!.text = "\(likeCount)"
    cell.dislikeButton.titleLabel!.text = "\(dislikeCount)"
    return cell
}

问题更新后,您可以使用awakeFromNib来完成此任务......

class UserFeedCell: PFTableViewCell {

@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var dislikeButton: UIButton!

override func awakeFromNib() {
    super.awakeFromNib()
    likeButton.titleLabel!.text = "\(likeCount)"
    dislikeButton.titleLabel!.text = "\(dislikeCount)"
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

答案 1 :(得分:0)

viewDidLoad不适合在UITableViewCell设置属性。您必须等待iOS要求单元格,然后您可以在单元格上设置属性并将其返回。 cellForRowAtIndexPath是正确的方法。您还需要确保为正确的单元格正确设置属性(使用indexPath.row)。