我有一个UITableView其中每个单元格从我的模型类获取其数据,这是我的TableViewController类中的一个数组。每个单元格的模型设置为cellForRowAtIndexPath。我的模型有一个“isFavorited”属性。我的自定义单元类有一个带有星形图像的UIButton。根据模型更新UIButton的图像
如果model.isFavorited == false,UIButton图像是灰色的星星。
如果model.sFavorited == true,UIButton图像应该变成一颗黄色的星星。
到目前为止,我试图接近这个像这样:
private let normal = UIImage(named: "star")
private let selection = UIImage(named: "star highlighted")
class CustomCell: UITableViewCell {
var model: Model? {
didSet{
favoriteButton.selected = (model?.isFavorite)!
}
}
@IBOutlet var favoriteButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
favoriteButton.adjustsImageWhenHighlighted = true
favoriteButton.setImage(normal, forState: .Normal)
favoriteButton.setImage(selection, forState: .Highlighted)
favoriteButton.setImage(selection, forState: .Selected)
}
@IBAction func favoriteTapped(sender: AnyObject) {
//UPDATE THE MODEL
model?.isFavorite = !(model?.isFavorite)!
}
}
此代码成功地改变了从灰色到黄色,反之亦然感谢一个明星didSet被称为用值来更新favoriteButton.selected
布尔从(model?.isFavorite)!
。然而,当我通过我的tableview浏览足够多,并尝试返回到我偏爱的特定单元格时,图像将重新出现为不合适的(灰色星形而不是黄色星形)。
如果我的模型正在更新,当我点击按钮时,由于此更改而在didSet期间调整了UIButton的图像,为什么当滚动回到此单元格时它会恢复为默认状态?
编辑: 我在的cellForRowAtIndexPath
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomCell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CustomCell
cell.model = modelArray[indexPath.row]
return cell
}
我知道这里发生了什么。你能从'cellForRowAtIndexPath'发布你的代码,这样我可以用代码来回答吗? – rigdonmr
查看我的更新后的代码。 – iOShepherd
是啊..现在挠我的头。其实对我来说很好。第一步是找出问题出在哪里。我会在该didSet回调中放置一个打印语句来打印model.isFavorite值。顺便说一下,使用'model!.isFavorite',而不是'(model?.isFavorite)!',后者是矛盾的 – rigdonmr