UIView-Shimmer
可通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile
pod 'UIView-Shimmer', '~> 1.0'
然后导入
import UIView_Shimmer
UIView-Shimmer
可通过 Swift Package Manager 获取。
要添加软件包,请转到 File -> Swift Packages -> Add Package Dependancy
name: "UIView-Shimmer"
url: https://github.com/omerfarukozturk/UIView-Shimmer.git
version: 1.0.2
如果您不想添加额外的依赖项,只需将 Sources 文件夹复制到您的项目中。
使任何视图遵循 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:)
扩展。此函数查找所有要设置为模板的后代子视图并应用动画。在调用之前,请确保视图已加载。
对于 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 文件。