<分区>
标签 ios swift uitableview
<分区>
我有一个 UITableView 列表,其中有一个按钮,上面写着“Click Me!”。我尝试遵循以下答案:https://stackoverflow.com/a/53043358/7746248将按钮与操作绑定(bind),但由于未知原因不起作用。
我已经检查了将按钮与事件绑定(bind)的其他方法,但我没有运气。
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
}
}
还有其他简单的方法吗?
最佳答案
在cellForRowAt
内添加目标,如下所示
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. button.addTarget(self, action: #selector(alertMethod), for: .touchUpInside)
return cell
}
@objc fileprivate func alertMethod() {
let alert = UIAlertController(title: "title", message: "Button Clicked!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
}
关于ios - Swift - 在 UITableViewCell 内单击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57056351/