首页 文章

单元格中的UIButton不会改变

提问于
浏览
1

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

Code background:

这是在UITableView控制器的 tableView(tableView: UITableView, cellForRowAtIndexPath: NSIndexPath) 中,控制器具有存储在'catch' 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 .

2 回答

  • 2

    不要直接为按钮设置图像和文本 . 使用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)
    }
    
  • 0

    使用以下更新图像:

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

    或者代码:

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

相关问题