我有一个 UITableView 和一些自定义单元格,到目前为止一切正常。我制作了一个自定义 UITableViewCell 类和带有 UIButton 的原型(prototype),我想在将单元格加载到表中时提供自定义图像和文本。
代码背景:
这是在 UITableView Controller 的 tableView(tableView: UITableView, cellForRowAtIndexPath: NSIndexPath)
中, Controller 将某些数据存储在“catch”ivar 中,而该 ivar 又具有要放置的图像按钮以及文本值。自定义 UITableViewCell
是 ImageTitleTableViewCell
,它仅具有 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/