如何按下button时在UITableviewCell中显示自定义视图?

我最近开始学习iOS开发,遇到了一些问题。

我有一个自定义单元格的tableview:标签,图像视图(默认情况下隐藏)和一个button。 我希望它的工作,以便单击button的单元格图像视图得到显示。 问题是,每次单元格被重用,图像视图显示为重用单元格。 我想让它工作,所以如果按下第一个单元格的button,只显示第一个单元格图像视图。 如果第一个和第三个单元格的button被按下,图像视图应该只显示第一行和第三行,而不是其他行。

我目前的解决scheme

class CustomTableViewCell: UITableViewCell { @IBOutlet var cellTitleLabel: UILabel! @IBOutlet var cellImageView: UIImageView! var showImageView = false @IBAction func showImageViewAction(sender: UIButton) { showImageView = true displayCell() } func displayCell() { if showImageView { cellImageView.hidden = false } else { cellImageView.hidden = true } } } 

而对于视图控制器:

 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 30 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as! CustomTableViewCell return cell } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let customCell = cell as! CustomTableViewCell customCell.displayCell() } 

任何关于如何创build的build议,以便重用单元格时隐藏图像视图?

如果你必须保存cellImageview.hidden状态,就这样做:

添加协议通知MainClass actionButton被按下:

 protocol customCellDelegate{ func actionButtonDidPressed(tag: Int, value: Bool) } 

比在你的CustomTableViewCell声明

 var delegate: customCellDelegate? 

并在@IBAction func showImageViewAction(sender: UIButton)添加:

 @IBAction func showImageViewAction(sender: UIButton) { cellImageView.hidden = ! cellImageView.hidden delegate?.actionButtonDidPressed(self.tag, value: imageCell.hidden) } 

在您的主视图使其符合customCellDelegate

 var status = [Bool]() func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let rowCount = 100 for _ in 0 ..< rowCount{ status.append(true) } return rowCount } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! customcell cell. cellImageView.hidden = true cell. cellImageView.hidden = status[indexPath.row] cell.delegate = self cell.tag = indexPath.row return cell } func actionButtonDidPressed(tag: Int, value: Bool) { status[tag] = value }