ios - 如何在多个类上调用同一个函数?

标签 ios swift protocols

我有一个带有 4 个 UIButton 的 UIViewController。用户可以点击这些 UIButtons 中的任何一个,然后会弹出一个 UIView。我想根据用户操作在持有 UIView 的类上添加 didAppear()didDisappear() 函数。如何在不使用枚举的情况下调用 didDisappear(),例如:

func didDisappear(view: EnumViews){
    switch view{
        case view0: myClassWithView0.didDisappear()
        case view1: myClassWithView1.didDisappear()
        case view2: myClassWithView2.didDisappear()
        case view3: myClassWithView3.didDisappear()
    }
}

现在我得到了 4 次重复数据。我知道我的类(class)有一个 UIView 函数,但是如何调用它呢?我做了一个协议(protocol):

protocol ViewProtocol{
    func didAppear()
    func didDisappear()
}

我让持有 UIView 的类符合该协议(protocol)。但是我不知道如何使用它,当我创建类时出现错误:

'myClassWithUIView' cannot be constructed because it has no accessible initializers

这些类都在一个数组中,我可以从 sender.tag 中识别出需要弹出哪个 UIView。理想情况下,我想要这样的东西:

@IBAction func bringNewUIView(_ sender: UIButton) {
let newView = myArrayOfClassesWithUIView[sender.tag]
newView.didAppear()
}

最佳答案

这里发生了很多事情。我将从简单的开始。

'myClassWithUIView' cannot be constructed because it has no accessible initializers

这只是意味着您没有您的类的初始值设定项。因此,在您的 myClassWithUIView 实现中,您需要有 init。我无法真正帮助您构建 init,因为我不知道该类的结构,但我假设您无论如何都知道该怎么做。

您的@IBAction 看起来不错。一旦你有了一组看起来应该可以工作的类。如果不是这种情况,请编辑您的帖子。

最后,对于您的 didDisappear 问题,您可以这样做:

func didDisappear(view: EnumViews) {
  //Check to see if this view conforms to your ViewProtocol (that's not a good name, btw)
  if let myClass = view as? ViewProtocol {
    //Since it does conform to ViewProtocol you can call didDisappear on it
    myClass.didDisappear()
  }
}

或者,如果您已经知道 didDisappear 函数始终传递符合 ViewProtocol 的 View ,为什么不更改参数并使其更容易呢?

func didDisappear(view: ViewProtocol) {
  view.didDisappear()
}

关于ios - 如何在多个类上调用同一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47563295/

相关文章:

swift - 不支持将某些协议(protocol)用作符合另一个协议(protocol)的具体类型

javascript - 有没有办法在phonegap中制作相框应用程序

android - 如何使用 Cordova 为 Android 和 iOS 设置应用程序图标

ios - Swift 中的通用委托(delegate)

swift - 在 Swift 2 中声明符合协议(protocol)的 UIView 类型的变量

networking - 如何在 CoAP 一致性测试套件中对测试用例进行分组

ios - 创建 NSSortDescriptor

ios - iOS 中 SQLite 的 ORM

ios - 在 containerView 中,如何访问包含 Swift 容器的 View Controller ?

ios - 为什么我的 UICollectionView 单元格在我的 swift ios 应用程序中不可点击?