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

How to show custom view in UITableviewCell when button pressed?

我最近开始学习 iOS 开发并且 运行 遇到了一些问题。

我有一个带有自定义单元格的表格视图:标签、图像视图(默认隐藏)和一个按钮。 我希望它能够工作,以便在单击单元格的按钮时显示图像视图。 问题是每次重用单元格时,都会显示重用单元格的图像视图。 我想让它工作,以便如果为第一个单元格按下按钮,则仅显示第一个单元格图像视图。如果按下第一个和第三个单元格的按钮,则图像视图应仅显示第一行和第三行,而不显示任何其他行。

我目前的解决方案:

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()
}

关于如何创建以便在重复使用单元格时隐藏图像视图的任何建议?

如果您必须保存 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)
}

在您的 mainView 中使其符合 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
}