defoification
defoification

Reputation: 313

Add a target to a UIButton from an external class

I have a UICollectionViewController(HomeViewController) with cells that each contain a collection view, and in each collection view's cells is a button(moreButton). I want to add the same target(handleMore) to each button, but the target exists in the UICollectionViewController.

This is how I tried to implement this behavior in the cell class that contains the collectionView:

cell.moreButton.addTarget(self, action: #selector(HomeViewController.handleMore), for: UIControlEvents.touchUpInside)

Also, is there a better way to do this? The button will possibly present a view controller.

Upvotes: 0

Views: 245

Answers (1)

Alfredo Luco G
Alfredo Luco G

Reputation: 974

I think that's no good idea to make a target from cellForRowAtIndexPath:. You should implement a delegate from your custom Cell Class, for example:

Protocol CustomCellDelegate{
    func didButtonPressed()
}

And you need to instantiate a var called delegate for implement your cell's button target:

class CustomCell: UITableViewCell{
   /...../
   var delegate: CustomCellDelegate? = nil

   override func AwakeFromNib(){
      super.awakeFromNib()
      self.button.addTarget(self, action: #selector(handleMore), for: .touchUpInside)
   }

  func handleMore(){
     if(self.delegate != nil){
        self.delegate.didButtonPressed()
     }
  }
}

This is an example for making something with your ViewController, so you first set up your cell's delegate to self (cell.delegate = self), second you must to implement the CustomCellDelegate on your ViewController. Otherwise if you only change something only in this own cell you can use the add target from your custom cell class.

Upvotes: 5

Related Questions