如何在UITableViewSwift 5中隐藏特定单元格的UIElement?

问题描述

我有一个TableView,为此我在xib中创建了一个单元格。该单元格具有标签和按钮。我想在需要的单元格的某些条件下显示标签并隐藏按钮。我该怎么办?

extension SourcesViewController: UITableViewDelegate,UITableViewDataSource {
...
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
        return 2
    }
func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SourceCell.reuseId,for: indexPath) as! SourceCell
        ...
return cell
}


class SourceCell: UITableViewCell {
...
@IBOutlet var logInLabel: UILabel!
@IBOutlet var logoutButton: UIButton!
...
@IBAction func logInlogoutButton(_ sender: Any) {
    //When I press this button I want to hide log out button and show label for current cell
   }
}

解决方法

我的自定义单元格

import Foundation
import UIKit

class MyCustomCell : UITableViewCell {
    @IBOutlet weak var myCustomLabel : UILabel!
    @IBOutlet weak var myCustomButton : UIButton!
    
    @IBAction func buttonClicked(_ sender : UIButton) {
        sender.isHidden = true
    }
}

TableView:

override func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "customCell",for: indexPath) as! MyCustomCell
        cell.myCustomLabel.text = "Row \(indexPath.row)"
        // Configure the cell...

        return cell
    }

输出内容如下:

enter image description here