3

I have a table view where each table view cell has an image.

I need to determine when an image view is completely visible on scroll. Additionally, if two images in two separate table view cells are completely visible at the same time, I want to only trigger an action for the first image.

I've thought of using willDisplay, but I've found that this only ever triggers once and it triggers as soon as the cell comes into view.

I also found this question, but it's specific to determining if the table view cell itself is completely visible, rather than a view within a table view cell.

What are my options? What is the best way of going around this?

iGatiTech
  • 2,142
  • 1
  • 17
  • 42
user023425
  • 131
  • 4
  • You can user let cells = tableView.visibleCells – Chaman Sharma Dec 06 '19 at 05:28
  • Set yourself as the scroll view delegate and examine the situation as scrolling takes place. – matt Dec 06 '19 at 06:00
  • @matt I'm not quite sure what you mean. I did just find out about `scrollViewDidEndDecelerating` and `scrollViewDidEndDragging`, so I now know when to trigger the calculation, but I'm still unsure of how to calculate whether or not the image is visible. – user023425 Dec 06 '19 at 06:02
  • Well you know the frame of all cells and the bounds offset of the table view. So it is easy to know what is fully visible. – matt Dec 06 '19 at 06:04
  • I think you have to set the images asynchronously on the image view and in the completion block you have to send notification to the main view and maintain a boolean value for the particular cell . – Arjun hastir Dec 06 '19 at 12:06

1 Answers1

1

Assuming you have set up view controller that manages image cells, here is a part of code for such controller, which is delegate of UITableView, that demos an approach of how to track becoming images visible. Hope it will be helpful.

@IBOutlet weak var tableView: UITableView!

override func viewDidAppear(_ animated: Bool) {
    self.verifyImagesVisibility()
}

func scrollViewDidScroll(_ scrollView: UIScrollView)  {
    self.verifyImagesVisibility()
}

private func verifyImagesVisibility() {
    for cell in self.tableView.visibleCells {
        if let imageView = cell.imageView {
            let visibleRect = self.tableView.bounds
            let imageRect = imageView.convert(imageView.bounds, to: tableView)

            imageView.layer.borderWidth = 4.0 // for test
            if visibleRect.contains(imageRect) {
                // do anything here for image completely shown
                imageView.layer.borderColor = UIColor.red.cgColor // for test
            } else {
                // do anything here for image become partially hidden
                imageView.layer.borderColor = UIColor.black.cgColor // for test
            }
        }
    }
}
Asperi
  • 123,447
  • 8
  • 131
  • 245