Spinnable
描述
Spinnable 是一个为 UIView 和 UIViewController 扩展的插件,它允许您通过默认实现或用户自定义的实现,方便地组织与带有旋转器的工作。
用法示例
以下代码片段显示了 SpinnableAddon 的基本用法,例如在从网络加载数据时
import UIKit
import Spinnable
class ViewController: UIViewController, Spinnable {
typealias SpinnerType = SpinnerView // Spinnable requirement: in this typealias, a type substitution takes place that satisfies
// the requirements of the Spinner protocol (an example implementation is given below)
var isLoaded: Bool = false // Spinnable requirement: this property is an indicator
// of whether data is being loaded at this moment.
override func viewDidLoad() {
super.viewDidLoad()
self.getDataFromNetwork()
}
private func getDataFromNetwork() {
self.showSpinner() // Set a spinner for the duration of a network request
let url = ...
let task = URLSession.shared.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
// ... Your code for processing data and responce from the server
self.hideSpinner() // Hide the spinner when a response is received from the server. We do it ON THE MAIN THREAD
}
}
task.resume()
}
}
showSpinner(on:configure:)
函数的覆盖版本允许您显式指定显示旋转器的视图,并且可以在旋转器显示时直接访问旋转器
满足旋转器协议要求的一个视图的实现示例
public class SpinnerView: Spinner {
public static func preparedSpinner() -> UIView {
let bg = UIView(frame: .init(x: 0, y: 0, width: 100, height: 100))
bg.backgroundColor = .clear
let plate = UIView(frame: .init(x: 0, y: 0, width: 100, height: 100))
plate.backgroundColor = .systemGray6
plate.idp_cornerRadius = 10
let indicator = UIActivityIndicatorView(style: .large)
bg.addSubview(plate)
plate.addSubview(indicator)
self.addCenteredConstraint(view: plate, superview: bg, heightOffset: -40)
self.addCenteredConstraint(view: indicator, superview: plate)
indicator.startAnimating()
return bg
}
private static func addCenteredConstraint(
view: UIView,
superview: UIView,
heightOffset: CGFloat = 0
) {
view.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = view.centerXAnchor.constraint(equalTo: superview.centerXAnchor)
let verticalConstraint = view.centerYAnchor.constraint(equalTo: superview.centerYAnchor, constant: heightOffset)
let widthConstraint = view.widthAnchor.constraint(equalToConstant: 100)
let heightConstraint = view.heightAnchor.constraint(equalToConstant: 100)
NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint])
}
}
要求
iOS 9+, Swift 3.0
安装
Spinnable可以通过CocoaPods获取。要安装它,只需在Podfile中添加以下行
pod "Spinnable"
SpinnableAdn可以通过Carthage获取。要安装它,只需在Cartfile中添加以下行
github "idapgroup/Spinnable"
授权
Spinnable采用新BSD授权。有关更多信息,请查看LICENSE文件。