【问题标题】:Loader using Protocol in Swift在 Swift 中使用协议的加载器
【发布时间】:2021-12-31 05:17:39
【问题描述】:

我想为视图控制器使用协议只是为了显示和隐藏加载器。在这部分我是成功的。但是如果加载器函数已经显示加载器,我想限制它的执行。

我为 API 请求调用 showLoader 函数。而且我不想隐藏加载程序,直到所有请求都得到响应。如果我将计数变量用作静态变量,我可以实现这一点吗?或者有没有其他方法可以在没有计数的情况下实现这一目标?甚至可能与否,请告知。

protocol Loader where Self: UIViewController {
    func showLoader()
    func hideLoader()
}

extension Loader {
    func showLoader() {
        if count == 0 {
            print("Show Loading")
        }
        count += 1
    }

    func hideLoader() {
        count -= 1
        if count < 1 {
            count = 0
            print("Hide Loading")
        }
    }
}

【问题讨论】:

  • 问题是什么?在哪里声明count
  • count 成为协议的一部分?
  • 我为您的问题编辑了更多内容。 @jnpdx
  • “将 count 变量用作静态变量”——这真的是您想要的吗?或者,您只是想知道如何像@JoakimDanielson 建议的那样制作协议的可变部分?
  • I would like to use the count variable as static 看起来像XY Problem。似乎您只需要一个计数器,它会根据showLoader/hideLoader 调用增加和减少,并根据计数器值显示/隐藏加载视图。尚不清楚为什么您需要一个协议,您能否向我们展示一些代码示例,说明您打算如何使用它,假设它有效?

标签: swift static protocols


【解决方案1】:

我认为你真的不需要关心这个。如果已经存在加载器,则可以在内部处理一个类,方法是在显示之前将其删除。

class Loader {
    // This is your view which can contain an animation or just the spinner
    private static var activityView: LoaderView!

    static func showLoader(onView view: UIView) {
        removeLoader()
        // The params are frame and superview
        activityView = LoaderView(with: view.bounds, view)
        view.addSubview(activityView)
        UIView.animate(withDuration: 0.25) {
            activityView.alpha = 1.0
        }
    }

    static func removeLoader() {
        UIView.animate(withDuration: 0.25) {
            // if exists it will be removed, if not is nil and nothing will happened.
            activityView?.removeFromSuperview()
        }
    }
}

【讨论】:

  • 我已经在使用加载器的基类了。但我正试图通过协议来实现这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-15
  • 1970-01-01
  • 2020-01-13
  • 1970-01-01
  • 1970-01-01
  • 2015-11-18
  • 2014-07-25
相关资源
最近更新 更多