Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add uibutton action in a collection view cell?

enter image description here

So I have this collection view with cells containing an edit button, located on the upper right corner. How do I wire up an action into it?

I tried adding cell.editbutton.addTarget in collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell But it doesn't detect the touchUpInside Event.

like image 922
Chris Mikkelsen Avatar asked Jan 04 '17 04:01

Chris Mikkelsen


3 Answers

Create the outlet of your UIButton in UICollectionViewCell, write In

func collectionView(_ collectionView: UICollectionView, 
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    cell.button.tag = indexPath.row
    cell.button.addTarget(self, 
        action: #selector(self.yourFunc(), 
        for: .touchUpInside)
}

func yourFunc(sender : UIButton){
    print(sender.tag)
}

Make sure userInteraction is enable for the button as well as for UICollectionViewCell.

like image 171
Himanshu Avatar answered Oct 17 '22 23:10

Himanshu


May be needful for you-

Write this code in cellForItemAtIndexPath

Swift 2.X

let editButton = UIButton(frame: CGRectMake(0, 20, 40,40))
editButton.setImage(UIImage(named: "editButton.png"), forState: UIControlState.Normal)
editButton.addTarget(self, action: #selector(editButtonTapped), forControlEvents: UIControlEvents.TouchUpInside)

cell.addSubview(editButton)

Swift 3.X

let editButton = UIButton(frame: CGRect(x:0, y:20, width:40,height:40))
editButton.setImage(UIImage(named: "editButton.png"), for: UIControlState.normal)
editButton.addTarget(self, action: #selector(editButtonTapped), for: UIControlEvents.touchUpInside)

cell.addSubview(editButton)

And perform your action-

override func viewDidLoad() {
       super.viewDidLoad()
}

@IBAction func editButtonTapped() -> Void {
    print("Hello Edit Button")
}
like image 27
iDeveloper Avatar answered Oct 18 '22 00:10

iDeveloper


On UICollectionView cell take button (Programmatically or using storyboard). Add action for that button in cell class file and declare delegate in that cell class file and call same delegate in button action method to perform edit action.

Then implement same delegate in ViewController in which you have created collection view

like image 1
Sayali Shinde Avatar answered Oct 17 '22 23:10

Sayali Shinde