如何在 UIElements 上正确使用占位符 API

How do I use placeholder API on UIElements correctly

我正在我的 Xcode 项目中实施一个名为 Skeleton View 的 API。有时当应用程序第一次加载时,加载 UI 元素需要更长的时间,因为数据来自 JSON 并且如果用户使用 4G 甚至是糟糕的互联网,将保持空白。此外,使用此 API 它会在每个未接收数据的 UI 元素上显示一个灰色视图动画占位符。

但是,我不知道如何检查 UIImage 何时接收到能够移除骨架效果并呈现图像的值。下面我会post一些图片。

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cellID") as! TableViewCell

            let model = arrCerveja[indexPath.row]

            cell.labelName.text = model.name
            cell.labelDetail.text = "Teor alcoólico: \(model.abv)"
            let resource = ImageResource(downloadURL: URL(string: "\(model.image_url)")!, cacheKey: model.image_url)

            if cell.imageViewCell.image != nil {
                cell.imageViewCell.kf.setImage(with: resource)
                cell.imageViewCell.hideSkeleton()
            }else{
               cell.imageViewCell.showAnimatedGradientSkeleton()

//The placeholder still there even when the images already got downloaded
//What I wanted was, while the UIImageView has no value, the placeholder 
//persists, but when receive the image the placeholder should be dismissed.
            }

            return cell
        }

这就是我在UI图片上得到的(它有一个模糊的动画经过):

我面临的问题是如何在每次图像加载后消除这种效果?

您需要在开始下载时启动动画(通常在您获取数据的函数之前):

view.startSkeletonAnimation()

此处的视图 属性 是您的视图控制器之一,SkeletonView 是递归的并且会为其中的所有视图设置动画。

然后在下载完成后(通常在重新加载 table 视图之前关闭,我假设所有图像都已下载并准备好显示)停止动画:

self.view.stopSkeletonAnimation()

骨架视图还为您提供了 UITableView 的委托:

public protocol SkeletonTableViewDataSource: UITableViewDataSource {
    func numSections(in collectionSkeletonView: UITableView) -> Int
    func collectionSkeletonView(_ skeletonView: UITableView, numberOfRowsInSection section: Int) -> Int
    func collectionSkeletonView(_ skeletonView: UITableView, cellIdenfierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier
}

正如 documentation 所说(阅读有关集合的部分以了解其工作原理):

This protocol inherits from UITableViewDataSource, so you can replace this protocol with the skeleton protocol.

您需要在 viewDidLoad() 函数中使您的 tableView skeletonnable:

tableView.isSkeletonable = true