如何在iOS中制作类似于Shimmer动画的反应加载骨架



我想要这样的Shimmer动画:https://gph.is/g/amWgbvj.(这个是使用库创建的:https://github.com/dvtng/react-loading-skeleton在WebApp中(

我尝试使用不透明度的GradientLayer通过所有子视图创建Shimmer动画:

gradientLayer.colors = [Colors.tokenDark20.cgColor, Colors.tokenDark10.cgColor, Colors.tokenDark20.cgColor]
gradientLayer.opacity = 0.5

但我得到了动画:https://gph.is/g/4L3K01P.

更多努力:

我试着使用图书馆:https://github.com/gonzalonunez/Skeleton,尝试从左到右链接动画,但我无法为所有子视图制作相同长度的渐变形状:

extension ShimmerExampleCell: SkeletonOwner {
var gradientLayers: [CAGradientLayer] {
return [imagePlaceholderView.gradientLayer, titlePlaceholderView.gradientLayer, subtitlePlaceholderView.gradientLayer]
}
func slide(to dir: SkeletonDirection, group: ((CAAnimationGroup) -> Void) = { _ in }) {
imagePlaceholderView.gradientLayer.slide(to: .right) { (animationGroup) in
animationGroup.beginTime = 0
}

titlePlaceholderView.gradientLayer.slide(to: .right) { (animationGroup) in
animationGroup.beginTime = 1.1
subtitlePlaceholderView.gradientLayer.add(animationGroup, forKey:  CAGradientLayer.kSlidingAnimationKey)
}
}
}

我在这里得到了动画:https://gph.is/g/ZPgPlXV

我是不是错误的方法来制作希姆动画?

请帮帮我!提前谢谢!

您可以尝试使用库SkeletonView;它应该可以帮助你在任何地方轻松实现微光动画。

视图控制器:

class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var data: [String] = []
override func viewDidLoad() {
super.viewDidLoad()

tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
tableView.delegate = self
tableView.dataSource = self

for value in 0..<20 {
self.data.append("(value) data")
self.tableView.reloadData() 
}
}

ViewController的扩展:

extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.labelName.text = data[indexPath.row]
return cell
}

UITableViewCell:在这里我设置SkeletonView 的显示或隐藏状态

class TableViewCell: UITableViewCell {
@IBOutlet weak var labelName: UILabel!
@IBOutlet weak var imgView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code

let views = [labelName, imgView]
views.forEach {$0?.showHideSkeletonView(show: true)}

DispatchQueue.main.asyncAfter(deadline: .now()+3) { 
views.forEach {$0?.showHideSkeletonView(show: false)}
}
}

ConfigSkeleton:在这里,我为skeletonView添加了一个用于设置、动画和颜色的函数。

import SkeletonView
extension UIView {
func setSkeletonView() {
self.isSkeletonable = true
}
func showHideSkeletonView(show: Bool) {
if show {
let gradient = SkeletonGradient(baseColor: UIColor.clouds)
let animation = SkeletonAnimationBuilder().makeSlidingAnimation(withDirection: .topLeftBottomRight)
self.showAnimatedGradientSkeleton(usingGradient: gradient, animation: animation)
} else {
self.hideSkeleton()
}
}