ViewStates
ViewStates 使得创建带有加载、成功、无数据和错误状态的视图变得简单。它还具有操作按钮,因此我们可以执行一些操作,例如 导航到其他视图
,或 重试
异步任务。UI 可以轻松自定义。
预览
要求
- iOS 9.0+
- Xcode 9.0+
- Swift 4.0+
安装
CocoaPods
ViewStates 通过 CocoaPods 提供访问。要安装它,只需将以下行添加到 Podfile 中
pod 'ViewStates'
手册
您只需将2个文件 ViewState.swift
和 UIImage+Gif.swift
复制到项目中的 ViewStates/Classes/
目录。对于 UIImage+Gif.swift
,我是从以下仓库中获取的:https://github.com/swiftgif/SwiftGif。该库的目的是在加载状态下使GIF图像动画化。我想感谢作者们。
使用方法
基本用法
- 初始化ViewState,并将您想要显示ViewState的视图设置为ViewState的
parentView
class ViewController: UIViewController {
let viewState = ViewState()
override func viewDidLoad() {
super.viewDidLoad()
viewState.parentView = self.view
}
}
- 显示加载状态
viewState.showLoadingState(loadingMessage: "Loading...")
- 异步任务成功完成时,隐藏ViewState
viewState.hideViewState()
- 异步任务失败时,我们可以显示错误状态
self.viewState.showErrorState("Oops! Something went wrong...")
- 从异步任务中获取到无数据要显示时,我们可以显示
NoData
状态
self.viewState.showNoDataState("There is nothing to display")
高级用法
- 使用图像和操作按钮显示
NoData
状态
self.viewState.showNoDataState("There is nothing to display", noDataImage: UIImage(named: "no_data",
actionButtonTitle: "CREATE ONE", actionHandler: {
// The code to open the view to create one
}
- 使用图像和
重试
按钮显示错误状态
self.viewState.showErrorState("Oops! Something went wrong...", errorImage: UIImage(named: "error",
actionButtonTitle: "RETRY", actionHandler: {
self.loadData()
})
样式
您可以为应用中所有视图的ViewState设置自定义主题,您可以在AppDelegate
或其他您希望的位置进行设置。
let theme = ViewStateTheming()
theme.messageTextColor = .red
theme.actionButtonBackgroundColor = .green
theme.actionButtonTitleColor = .white
....
ViewState.useCustomeTheme(theme)
以下是我们可以更改的所有属性
class ViewStateTheming {
// Background color of the ViewState view
var backgroundColor = UIColor.white
// The message label style
var messageTextColor = UIColor.darkText
var messageTextAlignment = NSTextAlignment.center
var messageTextFont = UIFont.systemFont(ofSize: 15)
// The action button style
var actionButtonBackgroundColor = UIColor.white
var actionButtonTitleColor = UIColor.blue
var actionButtonFont = UIFont.boldSystemFont(ofSize: 15)
var actionButtonInset = UIEdgeInsets(top: 5, left: 20, bottom: 5, right: 20)
var actionButtonCornerRadius: CGFloat = 5
// If there is no GIF image, the iOS UIActivityIndicatorView will be used
var defaultLoadingSpinnerColor = UIColor.gray
// Default image and loading text. This can be set when changing state for a special view
var defaultLoadingMessage = ""
var defaultLoadingImageName: String?
var defaultErrorImage: UIImage?
var defaultNoDataImage: UIImage?
}
作者
谭汉福([email protected])
许可证
ViewModels遵循MIT许可。有关更多信息,请参阅LICENSE文件。