【问题标题】:UIButton in cell doesn't change单元格中的 UIButton 不会改变
【发布时间】:2015-08-11 09:57:08
【问题描述】:

我有一个 UITableView 和一些自定义单元格,到目前为止一切正常。我使用 UIButton 制作了一个自定义 UITableViewCell 类和原型,我想在将单元格加载到表格时提供自定义图像和文本。

代码背景:

这是在 UITableView 控制器的tableView(tableView: UITableView, cellForRowAtIndexPath: NSIndexPath) 中,控制器将某些数据存储在“catch”ivar 中,该 ivar 又具有要放置在按钮中的图像以及文本值。自定义UITableViewCellImageTitleTableViewCell,它仅具有如下所示的 IBOutlet 属性 - 两个标签和 myImageButton UIButton。

let cell: ImageTitleTableViewCell = tableView.dequeueReusableCellWithIdentifier("ImageTitleCell") as! ImageTitleTableViewCell
//Happily this never triggers.
assert(cell.myImageButton.imageView != nil, "Bad image button.")
cell.myImageButton.imageView!.image = catch.image
if catch.image != nil {
    cell.myImageButton.titleLabel!.text = ""
    println(cell.myImageButton.titleLabel!.text)
    // Always logs the the default value of the button text which isn't "".
} else {
    cell.myImageButton.titleLabel!.text = "None."
}
//These two work fine though.
cell.speciesLabel.text = catch.species
cell.dateLabel.text = catch.date.description
return cell

它也不会放入图像中。我们可以确信 catch.image 在我测试时确实包含有效的 UIImage。

【问题讨论】:

    标签: ios swift uitableview uibutton


    【解决方案1】:

    不要直接设置按钮的图像和文本。使用func set<X>(forState:)func <X>ForState:) 方法。

    cell.myImageButton.setImage(catch.image, forState:.Normal)
    

    cell.myImageButton.setTitle("", forState:.Normal)
    

    代码变成

    cell.myImageButton.setImage(catch.image, forState:.Normal)
    if catch.image != nil {
        cell.myImageButton.setTitle("", forState:.Normal)
        println(cell.myImageButton.titleForState(.Normal))
        // Always logs the the default value of the button text which isn't "".
    } else { 
        cell.myImageButton.setTitle("None.", forState:.Normal)
    }
    

    【讨论】:

    • 哇,如果不检查文档,我什么都不记得了。我在答案的第一个版本中使用了ControlState 而不仅仅是State
    • 谢谢,这显然是 /the/ 方法。只是为了澄清,为什么我的方法不起作用?文档表明我正在访问的属性是可读写的,它应该可以正常工作。
    • @RichardBirkett 我不知道内部结构,但作为猜测......UIControlStateNormal 的值被设置为nil,所以当按钮正常显示时它替换了nil .
    • 谢谢。我想我使用的只是更“实时”而不是在准备中。
    【解决方案2】:

    使用以下更新图像:

    cell.myImageButton.setImage(UIImage(named: "imgTest.png"), forState: UIControlState.Normal) 
    

    或为您的代码:

    cell.myImageButton.setImage(catch.image, forState: UIControlState.Normal) 
    

    【讨论】:

      猜你喜欢
      • 2014-10-02
      • 1970-01-01
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      相关资源
      最近更新 更多