Edric Chen Edric Chen - 4 years ago 119
Swift Question

Getting which UIcollectionviewcell the textview im touching is in

I have a UICollectionView and each cell has a UITextView. I'm trying to make it possible to delete the entire cell when long pressing the text in a TextView and selecting Delete from the context menu.

I know I can override Delete by overriding

func delete(_ sender: Any?) {//I want to delete cell from here}


and

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(delete(_:))
{
return true
}
return super.canPerformAction(action, withSender: sender)
}


I just don't know how to find the current cell I am in.

Answer Source

Swift 3 Solution: So some people were close, but everyone led me down the right path almost. The solution doesn't exactly answer my question, but it could be combined with a gesturerecognizer to answer the question specifically.

So my solution is based on how my code is formatted and may need to be tweaked for anyone else.

First: From the UICollectionViewCell subclass, where my textview is implemented of course, I overrode the built in delete function. From there is created a variable that is instantiated with with the cells superview, which is a UICollectionView. This allows me to get the indexPath for the cell. From there I also create a variable that is instantiated with the UIView for where my UICollectionView is located. From there I created a function inside my UIView that takes in a IndexPath and deletes the cell.

Inside UICollectionViewCell:

override func delete(_ sender: Any?) {
    let cv = self.superview as! UICollectionView
    let indexPath = cv.indexPath(for: self)
    let view = self.superview?.superview as! UIView
    view.delCell(indexPath!)
}

Inside UIView:

func delCell(indexPath: IndexPath) {/*code for cell removal here*/}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download