我有一个tableview单元格,在每个单元格中都有类似按钮。
我想如果用户点击单元格的like按钮,它会改变按钮图像。
这是我的代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Result", forIndexPath: indexPath) as! ResultTableViewCell
cell.likebutton.tag = indexPath.row
return cell
}
和功能
@IBAction func printTag(sender: AnyObject) {
let cell = tableView.dequeueReusableCellWithIdentifier("Result", forIndexPath: indexPath) as! ResultTableViewCell
cell.likebutton.setImage(UIImage(named: "clicklike"), forState: UIControlState.Normal)
}
任何修复?
答案 0 :(得分:1)
除了dequeueReusableCellWithIdentifier
之外,绝不应该从cellForRowAtIndexPath
拨打@IBAction
。流程是:
table.reloadRowsAtIndexPaths()
处理程序因此触发NSIndexPath
cellForRowAtIndexPath
// This is a data model. I'm not sure you understand how critical this is.
var isLikedAtIndex = [ false, false, false ] // Example only: array of 3 booleans
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Result", forIndexPath: indexPath) as! ResultTableViewCell
if isLikedAtIndex(indexPath.row) {
cell.likebutton.setImage(someLikedImage)
}
else {
cell.likebutton.setImage(someNotLikedImage)
}
cell.likebutton.tag = indexPath.row
return cell
}
@IBAction func clickLike(sender: UIButton) {
isLikedAtIndexPath(sender.tag) = true // !! The model !! Save your data!
let myClickedIndexPath = NSIndexPath(forRow: sender.tag, inSection: 0)
table.reloadRowsAtIndexPaths([myClickedIndexPath], withRowAnimation: .Automatic)
}
,然后需要咨询您的模型,请注意该特定行位于'喜欢'在返回单元格之前,以不同方式呈现单元格中的图像。考虑到你的尝试,这可能比你想象的要多得多。这对你有什么用?
修改
我发现你仍然在寻找快捷方式而不是建模数据。你需要这样的东西:
#lang racket
(require 2htdp/universe 2htdp/image)
(provide big-bang
to-draw
stop-when
empty-scene
(rename-out [on-tick new-name]))
答案 1 :(得分:1)
发件人应该是 likebutton 的引用,因此您应该能够执行以下操作:
sender.setImage(UIImage(named: "clicklike"), forState: UIControlState.Normal)
我认为你这样做是错误的。当重新使用单元格时, likebutton 将最终处于新 indexPath 的错误状态。 likebutton 的状态应在
中确定 tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
或
tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
所以,你不应该将单元格出列,以便像这样更改按钮。相反,您应该更改确定按钮状态的属性,然后调用reloadRowsAtIndexPaths(indexPaths: [NSIndexPath], withRowAnimation animation: UITableViewRowAnimation)
我不确定您在哪里获得 indexPath ,但您可以使用发件人来确定它,如下所示:
let rootViewPoint = sender.superview?.convertPoint(sender.center, toView: self.tableView.center)
let indexPath = self.tableView.indexPathForRowAtPoint(rootViewPoint)
然后,您可以使用 indexPath 来确定需要更改模型的哪个实例,进行更改,然后调用:
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)