How to add a button with click event on UITableViewCell in Swift?

前端 未结 3 736
耶瑟儿~
耶瑟儿~ 2020-12-23 16:34

In my main page, I created a xib file for UITableViewCell. I\'m loading the cell from that xib file and its working fine.

Inside of the cell I have some labels and

3条回答
  •  感动是毒
    2020-12-23 16:43

    Popular patterns for solving this problem are closures and delegates. If you want to use closures, you would do something like this:

    final class MyCell: UITableViewCell {
        var actionBlock: (() -> Void)? = nil
    

    then

        @IBAction func didTapButton(sender: UIButton) {
            actionBlock?()
        }
    

    then in your tableview delegate:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell {
    
        let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier") as? MyCell
        cell?.actionBlock = {
           //Do whatever you want to do when the button is tapped here
        }
    

    A popular alternative is to use the delegate pattern:

        protocol MyCellDelegate: class {
            func didTapButtonInCell(_ cell: MyCell)
        }
    
        final class MyCell: UITableViewCell {
            weak var delegate: MyCellDelegate?
    

    then

        @IBAction func didTapButton(sender: UIButton) {
            delegate?.didTapButtonInCell(self)
        }
    

    .. Now in your view controller:

    then in your tableview delegate:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) - > UITableViewCell {
    
        let cell = tableView.dequeueReusableCellWithIdentifier("MyCellIdentifier") as? MyCell
        cell?.delegate = self
    

    And add conformance to the protocol like this:

    extension MyViewController: MyCellDelegate {
        didTapButtonInCell(_ cell: MyCell) {
           //Do whatever you want to do when the button is tapped here
        }
    }
    

    Hope this helps!

提交回复
热议问题