【发布时间】:2016-07-07 23:09:30
【问题描述】:
我有一个 UITableView,其中每个单元格都从我的模型类中获取其数据,这是我的 TableViewController 类中的一个数组。每个单元格的模型在 cellForRowAtIndexPath 中设置。我的模型有一个“isFavorited”属性。我的自定义单元格类有一个带有星形图像的 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 以使用来自 (model?.isFavorite)! 的值更新 favoriteButton.selected 布尔值,此代码成功地将星形从灰色变为黄色,反之亦然。
但是,当我在表格视图中滚动足够远并尝试返回到我收藏的特定单元格时,该图像将重新显示为不受欢迎(灰色星而不是黄色星)。
如果当我点击按钮时我的模型正在更新,并且 UIButton 的图像由于此更改而在 didSet 期间调整,为什么滚动回此单元格时它会恢复到默认状态??
编辑: 我在 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发布你的代码,以便我用代码回答吗? -
查看我更新后的代码。
-
是的..现在挠头了。实际上对我来说看起来不错。第一步是弄清楚问题出在哪里。我会在 didSet 回调中放置一个打印语句来打印 model.isFavorite 值。顺便说一句,使用
model!.isFavorite,而不是(model?.isFavorite)!,后者是矛盾的
标签: swift uitableview uibutton