【问题标题】:Trouble changing UIButton image无法更改 UIButton 图像
【发布时间】:2016-01-24 21:41:50
【问题描述】:

我有一个 tableView,我在其中发布用户提要,并在单元格视图中添加了一个心形按钮。我为单元格视图创建了一个类,并在那里声明了我的按钮的@IBOutlet。然后在表格视图的cellForRowAtIndexPath 中,我调用了按钮并将indexpath.row 设置为按钮本身的标记号。然后我添加了一个要完成的操作的目标并创建了我的@IBAction。现在我正在尝试将心形按钮的图像外观更改为红色,但没有任何反应。通过发送方将 UIImage 传递给按钮是否存在问题。我没有错误。 if like = 语句工作正常。这是我的代码:

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

        cell.heartButton.tag = indexPath.row
        cell.heartButton.addTarget(self, action: "liked:", forControlEvents: .TouchUpInside)
return cell
}

@IBAction func liked (sender: UIButton){

        if like == false{
        sender.imageView?.image = UIImage(contentsOfFile: "red-heart.png")
            like = true
        }
        else{
            sender.imageView?.image = UIImage(contentsOfFile: "white-heart-hi.png")
            like = false
        }
       // self.tableView.reloadData()
    }

【问题讨论】:

    标签: ios swift uitableview uibutton


    【解决方案1】:

    试试这个。

        if like == false{
            sender.setImage(UIImage(named: "red-heart.png"), forState: .Normal)
            like = true
        } else {
            sender.setImage.setImage(UIImage(named: "white-heart-hi.png"), forState: .Normal)
            like = false
        }
    

    【讨论】:

    • 甜蜜。很高兴我能提供帮助。只要有机会,接受这个答案就会很棒。
    【解决方案2】:

    这是一个非常简单的错误。您将目标函数声明为“liked:”,但您的函数声明为“liked”。注意第二次缺少冒号。这很关键,应该可以解决问题。如果这不能解决问题,请确保您已声明

    var like = false
    

    如果这仍然不起作用,请发表评论,我将继续提供帮助。如果它确实有效,请不要忘记检查我的答案。

    【讨论】:

    • Kegham 的liked(_:) 函数对应的选择器是liked:,带有冒号。
    • 更多信息请见Interacting with Objective-C APIs
    • var like = false 是全局声明的。我很遗憾我没有错误。我无法删除该列。我会得到一个错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多