R.Tech R.Tech - 6 months ago 24
Swift Question

Hide View in UICollectionViewCell

Can anyone tell my it won't hide my UIView in the simulator?
The code is functioning and it prints the numbers I added to the functions but it still doesn't work.

Basically I want to tap the cell and the greyView in the cell should disappear.

override func viewDidLoad() {
super.viewDidLoad()

let lpgr = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTap(_:)))
lpgr.numberOfTapsRequired = 1
lpgr.delaysTouchesBegan = true
lpgr.delegate = self
AlarmCollection.addGestureRecognizer(lpgr)

}


// MARK: UICollectionViewCell

func handleTap(gestureReconizer: UITapGestureRecognizer) {
if gestureReconizer.state != UIGestureRecognizerState.Ended {
return
}

let p = gestureReconizer.locationInView(AlarmCollection)
let indexPath = AlarmCollection.indexPathForItemAtPoint(p)

if let index = indexPath {
var cell = AlarmCollection.cellForItemAtIndexPath(index)
// do stuff with your cell, for example print the indexPath
print(index.row)
updateView(indexPath!)
} else {
print("Could not find index path")
}
}



func updateView(indexPath: NSIndexPath) {
let cell = AlarmCollection.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! AlarmItemCell
cell.greyView.hidden = true
print("2")

}


EDIT:

// MARK: UICollectionViewCell



func handleTap(gestureReconizer: UITapGestureRecognizer) {
if gestureReconizer.state != UIGestureRecognizerState.Ended {
return
}

let p = gestureReconizer.locationInView(AlarmCollection)
let indexPath = AlarmCollection.indexPathForItemAtPoint(p)

if let index = indexPath {
var cell = AlarmItemCell()
// do stuff with your cell, for example print the indexPath
print(index.row)
updateView()
} else {
print("Could not find index path")
}
}




func updateView(cell: UICollectionViewCell) {
if let cell = cell as? AlarmItemCell {
cell.greyView.hidden = true
}
print("2")
}


EDIT 2:

if let index = indexPath {
let cell = AlarmCollection.cellForItemAtIndexPath(index)
updateView(cell!)


}

Answer

You should be able to use the cell that you are getting from your collection view to reference the greyView.

For example, change your updateView function to:

func updateView(cell: UICollectionViewCell) {
    if let cell = cell as? AlarmItemCell {
      cell.greyView.hidden = true
    }
    print("2")
}

Then pass the cell you got here var cell = AlarmCollection.cellForItemAtIndexPath(index) to the function. The way you are doing it now isn't grabbing the correct cell as far as I can tell.

EDIT:

if let index = indexPath, 
   let cell = AlarmCollection.cellForItemAtIndexPath(index) {
    updateView(cell)
} else {
    print("Could not find index path or cell")
}