【问题标题】:UIButton inside TableViewCell couldn't be set image after clickedUITableViewCell中的UIButton点击后无法设置图片
【发布时间】:2017-12-20 10:33:44
【问题描述】:

UITableViewCell 内的按钮不响应其 clicked 方法内的 setImage 方法。这是 TableView 的 cellForRowAt 部分。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell=tableView.dequeueReusableCell(withIdentifier: "BroadcastViewCell", for: indexPath) as!BroadcastViewCell
    var show=self.week?[selectedIndex].shows?[indexPath.item]
    cell.myLabel.text=show?.programName
    if let resim=show?.thumbURL{
        cell.myImage.downloadImage(from: resim)
    }
    cell.notifyButton.tag = indexPath.row
    cell.notifyButton.setImage( UIImage(named:"icnAlarm"), for: .normal)
    cell.notifyButton.setImage( UIImage(named:"icnAlarmCheck"), for: .selected)

    if (self.notifications?.contains(where: {$0.identifier == (show?.airDate)!+(show?.airTime)!}))!
    {
        cell.notifyButton.isSelected=true
    }else
    {
        cell.notifyButton.isSelected=false
    }
    cell.notifyButton.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside)
    return cell;
}

我只是在 buttonClicked 实现中设置了它的选中状态。

func buttonClicked(sender:UIButton)
{
    sender.isSelected=true
}

但是图像在它之后并没有改变。它仅在对其特定行调用 cellForRowAt 方法后更改。我不明白为什么它对同一代码部分的响应不同。感谢您的帮助。

【问题讨论】:

  • 查看我对这篇文章的回答 - (link)[stackoverflow.com/questions/44393575/… - 它使用两个图像作为 UIButtonUITableViewCell 中创建一个选中/未选中的“复选框”,其中应该非常接近你想要做的事情。

标签: ios swift uitableview swift3 uibutton


【解决方案1】:

你必须告诉按钮做什么:

func buttonClicked(sender:UIButton)
{
    if myButton.isSelected {
         myButton.isSelected = false
    }else{
       myButton.isSelected = true
    }
}

将您的按钮配置为自定义:

let myButton = UIButton(type: .custom)

或在属性检查器中:

【讨论】:

  • selected 在我的版本中已重命名为 isSelected,在 cellForRowAt 方法中设置 isSelected true 也可以正常工作。
  • 问题:你的 buttonClicked 方法是否被触发了?顺便说一句,尝试将您的按钮类型设置为自定义
  • 是的,它被触发了。此外,当我打开 Debug View Hierarchy 时,我可以看到按钮图像已成功更改。但它不会响应实际设备中的这种变化。
  • 所以,问题是您看不到与按钮选择状态相关联的图像。您是否尝试将按钮更改为 .custom?或在属性检查器中的界面构建器中 -> 类型 -> 自定义?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多