Swift-在UITableViewCell内单击获取按钮

时间:2019-07-16 11:35:39

标签: ios swift uitableview

我有一个带有按钮的UITableView列表,上面显示“ Click Me!”。我尝试按照以下答案进行操作:https://stackoverflow.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
    }

}

enter image description here

还有其他简单的方法吗?

1 个答案:

答案 0 :(得分:0)

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