ios - 单元格中的 UIButton 没有改变

标签 ios swift uitableview uibutton

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

代码背景:

这是在 UITableView Controller 的 tableView(tableView: UITableView, cellForRowAtIndexPath: NSIndexPath) 中, Controller 将某些数据存储在“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。

最佳答案

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

关于ios - 单元格中的 UIButton 没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31938668/

相关文章:

ios - 使用 Swift 从单元格中检索图像以在 FB/Twitter 上共享

iOS - 默认事件加载器,如 "please wait"

javascript - 类方法在未被调用的情况下被触发

ios - 函数未在 swift 中从 NSTimer 选择器调用(在模拟器中工作,但不在设备中工作)

arrays - 将数组指针传递给另一个类并为将来保留一个引用 - Swift

iphone - 为什么我的 UITableView 每个部分只显示两行?

ios - iOS 中 SQLite 的 ORM

iphone - 如何在 NSMutableDictionary 上使用 writeToFile 方法?

ios - 从应用程序扩展打印到控制台

ios - UITableView heightForHeaderInSection 不工作