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

前端 未结 3 734
耶瑟儿~
耶瑟儿~ 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!

    0 讨论(0)
  • 2020-12-23 16:57

    All patterns above are fine. my two cents, in case You add by code (for example multiple different cells and so on..) there is a FAR simple solution.

    As buttons allow to specify a "target" You can pass directly the controller AND action to cell/button when setting it.

    In controller:

    let selector = #selector(self.myBtnAction)
    setupCellWith(target: self, selector: selector)
    

    ...

    in custom cell with button:

    final func setupCellWith(target: Any? selector: Selector){
           btn.addTarget(target, 
            action: selector,
           for: .touchUpInside)
    
    }
    
    0 讨论(0)
  • 2020-12-23 16:59

    2 am answer: You're over thinking this. Create a custom TableViewCell class; set the prototype cell class to your new custom class; and then create an IBAction.

    0 讨论(0)
提交回复
热议问题