要通过单击同一UIButton上的另一个UIButton来禁用UITableViewCell,你需要处理UIButton的点击事件,并在事件处理程序中更新UITableViewCell的状态。以下是实现这一功能的步骤和示例代码:
isUserInteractionEnabled
属性。import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let tableView = UITableView()
let button1 = UIButton(type: .system)
let button2 = UIButton(type: .system)
var isCellEnabled = true
override func viewDidLoad() {
super.viewDidLoad()
// 设置按钮标题
button1.setTitle("Enable Cell", for: .normal)
button2.setTitle("Disable Cell", for: .normal)
// 设置按钮点击事件
button1.addTarget(self, action: #selector(enableCell), for: .touchUpInside)
button2.addTarget(self, action: #selector(disableCell), for: .touchUpInside)
// 设置表格视图
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
// 添加按钮和表格视图到视图
view.addSubview(tableView)
view.addSubview(button1)
view.addSubview(button2)
// 布局约束
tableView.translatesAutoresizingMaskIntoConstraints = false
button1.translatesAutoresizingMaskIntoConstraints = false
button2.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: button1.bottomAnchor, constant: 20),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20),
button1.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
button1.centerXAnchor.constraint(equalTo: view.centerXAnchor),
button2.topAnchor.constraint(equalTo: button1.bottomAnchor, constant: 20),
button2.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
}
@objc func enableCell() {
isCellEnabled = true
tableView.reloadData()
}
@objc func disableCell() {
isCellEnabled = false
tableView.reloadData()
}
// UITableViewDataSource 方法
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Row \(indexPath.row)"
cell.isUserInteractionEnabled = isCellEnabled
return cell
}
}
enableCell
和 disableCell
方法分别设置 isCellEnabled
标志,并重新加载表格视图。cellForRowAt
方法中,根据 isCellEnabled
标志设置 cell.isUserInteractionEnabled
属性。通过这种方式,你可以实现通过单击不同的按钮来启用或禁用UITableViewCell的功能。
领取专属 10元无门槛券
手把手带您无忧上云