问题
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?
回答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
}
}
}
}
来源:https://stackoverflow.com/questions/59207206/determine-if-image-in-table-view-cell-is-completely-visible