Tolgay Toklar Tolgay Toklar - 7 months ago 28
Swift Question

Using protocol in Swift

I want to use protocols. I have a collection view and collection view cells which belongs to this collection view. I have a button in this cell. I want to call a method in collectionview class (not cell class) when user taps to this button.

I am defining my cell class with following code:

protocol testPro {
func replyClicked()
}

class MessageGalleryViewControllerCellCollectionViewCell: UICollectionViewCell {

var test1: testPro?

// ...
}


Then when user taps to button system calling following method in cell class.

func replyAction(sender:UIButton!)
{
test1?.replyClicked()

}


And My collection view class:

class ReceivedPhotosViewController: UIViewController,UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, testPro {

func replyClicked() {
print("clicked")
}
}


But I can't see any log like "clicked". So it is not working. Where is the problem?

JAL JAL
Answer

You are not assigning your test1 to your cell. In your cellForItemAtindexPath, put cell.test1 = self after instantiating the cell.