gpt4 book ai didi

swift - 如何实现单例微调器(事件指示器)?

转载 作者:行者123 更新时间:2023-11-30 10:40:51 26 4
gpt4 key购买 nike

我想实现一个单例微调器,因为任何具有 api 的应用程序都需要一个微调器。好吧,我可以编写一个旋转器自定义代码,但我的问题是,如果我想显示它,我应该编写下一行代码。

    let rosetaGIF = UIImage(named: "wheel.png")
let ind = MyIndicator(frame: CGRect(x: 0, y: 0, width: (rosetaGIF?.size.width)!/2, height: (rosetaGIF?.size.height)!/2), image: rosetaGIF!)
view.addSubview(ind)
view.alpha = 0.5
ind.startAnimating()

这不好,因为每次我想显示旋转器时我都必须放置这些行,好吧,我的旋转器类是下一个。我使用的是 swift 4.2

import UIKit

class MyIndicator: UIActivityIndicatorView {


let loadingView = UIView(frame: (UIApplication.shared.delegate?.window??.bounds)!)
let imageView = UIImageView()
let sizeView = UIViewController()

init(frame: CGRect, image: UIImage) {
super.init(frame: frame)

imageView.frame = bounds
imageView.image = image
imageView.contentMode = .scaleAspectFit
imageView.center = CGPoint(x: sizeView.view.frame.width/2, y: sizeView.view.frame.height/2)
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(imageView)
}

required init(coder: NSCoder) {
fatalError()
}

override func startAnimating()
{
isHidden = false
rotate()
}

override func stopAnimating()
{
isHidden = true
removeRotation()
}

private func rotate() {
let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.toValue = NSNumber(value: Double.pi * 1)
rotation.duration = 1
rotation.isCumulative = true
rotation.repeatCount = Float.greatestFiniteMagnitude
self.imageView.layer.add(rotation, forKey: "rotationAnimation")
}

private func removeRotation() {
self.imageView.layer.removeAnimation(forKey: "rotationAnimation")
}
}

我应该怎么做才能使旋转器成为单例?

谢谢

最佳答案

我建议您创建一个 util 类并将该类设为 Singleton。

import UIKit
class Util {
static let shared = Util()
private init(){}

var loader: MyIndicator?

func showLoader(view: UIView){
hideLoader()
let rosetaGIF = UIImage(named: "wheel.png")
loader = MyIndicator(frame: CGRect(x: 0, y: 0, width: (rosetaGIF?.size.width)!/2, height: (rosetaGIF?.size.height)!/2), image: rosetaGIF!)
view.addSubview(loader!)
view.alpha = 0.5
loader?.startAnimating()
}

func hideLoader(){
loader?.stopAnimating()
loader?.removeFromSuperview()
}
}

如何使用该类

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
Util.shared.showLoader(view: view) // for showing the loader
Util.shared.hideLoader() // for hiding the loader
}
}

关于swift - 如何实现单例微调器(事件指示器)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56830243/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com