UIView-Shimmer
为 iOS 应用程序轻松应用 shimmer 效果到任何视图和子视图
需求
- iOS 10+
安装
CocoaPods
UIView-Shimmer
可通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile 中
pod 'UIView-Shimmer', '~> 1.0'
然后导入
import UIView_Shimmer
Swift 包管理器
UIView-Shimmer
可以通过Swift 包管理器使用。
要添加包,请转到文件 -> Swift 包 -> 添加依赖
name: "UIView-Shimmer"
url: https://github.com/omerfarukozturk/UIView-Shimmer.git
version: 1.0.2
Manuel
如果不希望添加额外的依赖,只需将相关扩展复制到您的项目中。
UIView+Extensions.swift
UIView+Template.swift
UIView+Shimmer.swift
使用方法
闪动动画
让任何视图按照ShimmeringViewProtocol
执行,这表明闪动动画将应用于它或指定的子视图。在shimmeringAnimatedItems
中定义哪些子视图将被动画化。
final class SampleTableViewCell: UITableViewCell, ShimmeringViewProtocol {
@IBOutlet weak var profileImageBackgroundView: UIView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var actionButton: UIButton!
@IBOutlet weak var secondLabel: UILabel!
@IBOutlet weak var secondActionButton: UIButton!
var shimmeringAnimatedItems: [UIView] {
[
profileImageBackgroundView,
nameLabel,
actionButton,
secondLabel,
secondActionButton
]
}
}
或者,您可以扩展ShimmeringViewProtocol
来定义视图的类型将被动画化。
extension UILabel: ShimmeringViewProtocol { }
extension UIButton: ShimmeringViewProtocol { }
extension UITextView: ShimmeringViewProtocol { }
...
然后调用任何视图(基本上是父视图)的UIView
的扩展setShimmeringAnimationWithSubviews(template:superviewBackgroundColor:)
。此函数找到所有descendand子视图并应用动画。调用之前,请确保视图已加载。
对于UITableViewCell,要将其标记为模板,请在调用willDisplay
代理。
cell.setTemplateWithSubviews(isLoading, viewBackgroundColor: .systemBackground)
例如,在任务完成之后,可以使用template = false
参数来隐藏。隐藏模板(带闪动)动画时,不需要提供superviewBackgroundColor
值。
cell.setTemplateWithSubviews(template: false)
浅色主题 | 深色主题 |
---|---|
![]() |
![]() |
排除视图
您可以使用具有`ShimmeringViewProtocol`的`excludedItems`来设置在设置动画时将被排除的视图。
var excludedItems: Set<UIView> {
[nameLabel]
}
占位符
您只能通过设置animation: false
来设置模板视图而不带闪动动画。(例如,在SwiftUI中.redacted(reason: .placeholder)
)
view.setTemplateWithSubviews(true, animate: false)
默认 | 模板 |
---|---|
![]() |
![]() |
说明
模板视图(以及闪动效果)的帧是通过它们的intrinsicContentSize
或它们的布局约束来计算的。因此,您应该为UILabels
、UITextView
等设置占位值,或将它们的约束设置为直观地绘制它们的模板。
示例
示例项目展示如何使用它。拉取存储库并检查ShimmerExamples。
许可
UIView-Shimmer在MIT许可下可用。有关更多信息,请参阅LICENSE文件。