Determine if image in table view cell is completely visible

不羁岁月 提交于 2020-01-24 09:39:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!