【发布时间】:2015-10-29 10:07:19
【问题描述】:
我正在尝试实现代码以在单击该行时更改该行的按钮图像源。这是一个清单表视图。表视图分为多个部分。不知道我做错了什么:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//change tickBtn's image src to tick.png
print("in didselect")
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? CheckListCell {
let tickedImg = UIImage(named: "tick.png")
cell.tickBtn.setImage(tickedImg, forState: UIControlState.Selected)
//cell.tickBtn.alpha = 0
}
else{
print("in the else of didSelect")
}
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
//change tickBtn's image src to unTicked.png
print("in didDeselect")
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? CheckListCell{
let tickedImg = UIImage(named: "unTicked.png")
cell.tickBtn.setImage(tickedImg, forState: UIControlState.Selected)
//cell.tickBtn.alpha = 1
}
else{
print("in the else of didDeSelect")
}
}
我正在获取 didSelect 和 didDeSelect 的日志,但图像源没有改变。一定与我访问单元格的方式有关,我需要考虑该部分吗?
更新:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//change tickBtn's image src to tick.png
let cell = tableView.cellForRowAtIndexPath(indexPath) as? CheckListCell
cell!.cellTickedImage = UIImage(named: "tick.png")
self.checkListTableView.beginUpdates()
self.checkListTableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
self.checkListTableView.endUpdates()
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath) as? CheckListCell
cell!.cellTickedImage = UIImage(named: "unTicked.png")
self.checkListTableView.beginUpdates()
self.checkListTableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
self.checkListTableView.endUpdates()
}
class CheckListCell : UITableViewCell {
@IBOutlet weak var tickBtn: UIButton!
@IBOutlet weak var taskLbl: UILabel!
var cellTickedImage : UIImage?
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = checkListTableView.dequeueReusableCellWithIdentifier("CheckListCell", forIndexPath: indexPath) as! CheckListCell
cell.taskLbl?.text = checkListData[indexPath.section][indexPath.row]
cell.tickBtn.setImage(cell.cellTickedImage, forState: UIControlState.Normal)
cell.tickBtn.setImage(cell.cellTickedImage, forState: UIControlState.Highlighted)
//cell.tickBtn.titleLabel!.text = ""
return cell
}
【问题讨论】:
-
@DharmeshKheni 是的,就在具有所有 tableview 方法的视图控制器中
-
没有 alpha 值,你的 didselect 工作正常吗?
-
@Vijay 好的,所以当我点击一行时,我会按顺序获取 didDeSelect 和 didSelect 的日志。然后,如果我第二次、第三次、第四次点击该行,我只会得到 didSelect
-
所以我觉得你不能用这种方法实现你想要的。您需要重新加载特定行以切换刻度图像
-
你能在 indexpath 中显示你的单元格吗?
标签: ios swift uitableview sections