简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM