- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个带有 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/
我是一名优秀的程序员,十分优秀!