3

I have several UIButtons within UICollectionViewCells and I am unable to make them react to show a highlighted image as they do outside a UICollectionView.

There seems to be a delay and the highlighted image is only shown if you long press down on the button. This is a problem I have experienced before and would like to get to the bottom of it.

This is the code for setting a standard button image for normal and highlighted states.

   // inside GeneralCollectionViewCell
   let generalButton: UIButton = {
       let button = UIButton()
       button.translatesAutoresizingMaskIntoConstraints = false
       button.setImage(UIImage(named: "general_button")?.withRenderingMode(.alwaysOriginal), for: .normal)
       button.setImage(UIImage(named: "general_button_highlighted")?.withRenderingMode(.alwaysOriginal), for: .highlighted)
    return button
}()

   func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifer", for: indexPath) as! GeneralCollectionViewCell

       cell.addTarget(self, action: #selector(generalButtonHandler(_:)), for: .touchUpInside)

       return cell
   }

Any help on how to fix this annoying problem would be great.

Edward
  • 2,864
  • 2
  • 29
  • 39
  • Have you tried using an `@IBAction func` event handler such that when a button is pressed, an image is displayed? – ProgrammingEnthusiast Aug 29 '17 at 23:12
  • Can you try setting this main thread. – Vini App Aug 30 '17 at 00:40
  • Have you seen this? https://stackoverflow.com/a/31059885/3746301 – Shades Aug 30 '17 at 01:01
  • 1
    "There seems to be a delay and the highlighted image is only shown if you long press down on the button." - `UICollectionView` descends form `UIScrollView`, which has a boolean property called `delaysContentTuches`. – Nicolas Miari Aug 30 '17 at 05:18
  • Thanks for all the comments and your help. @NicolasMiari solved the issue for me. Had no idea UIScrollView had that property. – Edward Aug 30 '17 at 07:07
  • @Edward it's been around since the very beginning I think (iPhone OS 2.0?). It's purpose is to give the scroll view a hint of whether it should interpret a tap as the beginning of a scroll action right away, or wait just a little to see if it's actually directed at one if its subviews. – Nicolas Miari Aug 30 '17 at 07:17

0 Answers0