Kiruthiga
Kiruthiga

Reputation: 61

Create action for a button inside collection view

I have created a UICollection View inside a storyboard, I have created a button inside the cell, whenever I tap on the button I should filter the data as per my condition, so each and every buttons inside the cell will have different conditions, can anyone help me out with this issue ?? Iam using xcode 9 and swift 4.

Upvotes: 0

Views: 2556

Answers (3)

Nick
Nick

Reputation: 875

Try this for Objective c

Add below code at cellForRowAtIndexPath

cell.btnOk.tag = indexPath.row ;
[cell.btnOk addTarget:self action:@selector(OkBtnAction:) forControlEvents:UIControlEventTouchUpInside] ;

Than add the action of that button

-(IBAction)OkBtnAction:(id)sender
{
    UIButton* btn=(UIButton*)sender;
    NSLog(@"row: %ld",(long)btn.tag);

}

Upvotes: 0

Duncan C
Duncan C

Reputation: 131491

Create a custom UICollectionViewCell type. Wire up an IBAction to the cell.

Create a protocol that lets the cell notify the collection view that the user tapped a button. Have the action pass the tap to the delegate.

In your cellForItemAt() method, set the view controller as the delegate.

Now in your view controller handle the tap as desired.

Upvotes: 1

Arnab
Arnab

Reputation: 4356

Use addTarget of your button inside cellForItemAt:indexPath datasource and add a selector where action of the button will be defined. Add this button's tag, (add it same as your indexPath.row, that you can use to differentiate your button from collectionview)

cell.yourButton.addTarget(self, action: #selector(yourButtonTapped), for: .touchUpInside)
cell.yourButton.tag = indexPath.row

Now add the action of that button and inside that perform any action you need.

@IBAction func yourButtonTapped(_ sender: UIButton) {
    //perform action
}

Upvotes: 2

Related Questions