【发布时间】:2025-12-14 20:20:04
【问题描述】:
我有一个 UITableView 列表,其中有一个按钮,上面写着“点击我!”。我尝试按照以下答案进行操作:https://*.com/a/53043358/7746248 将按钮绑定到操作,但由于未知原因,这不起作用。
我已经检查了将按钮绑定到事件的其他方法,但我没有运气。
import UIKit
class SampleTableViewCell: UITableViewCell {
@IBOutlet weak var name: UILabel!
@IBOutlet weak var button: UIButton!
var tapCallback: (() -> Void)?
@IBAction func didTap(_ sender: Any) {
tapCallback?()
}
}
class TableViewController: UITableViewController {
var tableArray = ["New York", "Chicago", "North Island"]
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
self.clearsSelectionOnViewWillAppear = false
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.reloadData()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.tableArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SampleCell", for: indexPath) as! SampleTableViewCell
// Configure the cell...
cell.selectionStyle = UITableViewCell.SelectionStyle.none
let names = self.tableArray[indexPath.row]
cell.name.text = names
cell.tapCallback = {
// do stuff
DispatchQueue.main.async {
let alert = UIAlertController(title: "title", message: "Button Clicked!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
}
return cell
}
}
还有其他简单的方法吗?
【问题讨论】:
-
你只是想在 TableView 中的按钮方法对吗?
-
@KetanOdedra 是的,现在它不起作用。当在 TableView 中单击按钮时,我正在尝试创建一条警报消息。
-
我刚刚实现了这个,它工作正常
-
@truthsayer 我给你答案,给你del.dog/hexihodapa.m
-
@truthsayer 是的,我错过了给代表打电话,现在再次检查。您必须在 cellforrow 方法中调用单元委托 del.dog/hexihodapa
标签: ios swift uitableview