我遇到了无法覆盖函数的问题。
我的父类如下:
class A: UIViewController {
func parentalGate() {
let appearance = SCLAlertView.SCLAppearance(
kTitleFont: UIFont(name: "Futura", size: 20)!,
kTextFont: UIFont(name: "Futura", size: 14)!,
kButtonFont: UIFont(name: "Futura", size: 14)!,
showCloseButton: false
)
let alert = SCLAlertView(appearance: appearance)
let alert2 = SCLAlertView(appearance: appearance)
if (UserDefaults.standard.object(forKey: "language") as? String == "english") {
let txt = alert.addTextField("Enter third letter")
alert.addButton("Done") {
if ((txt.text == "P") || (txt.text == "p")) {
self.parentalGatefunctions()
} else {
alert2.addButton("Close", target: SCLAlertView(), selector: #selector(SCLAlertView.hideView))
alert2.showError("Incorrect letter entered", subTitle: "Try again")
}
}
alert.addButton("Close", target: SCLAlertView(), selector: #selector(SCLAlertView.hideView))
alert.showWarning("We need to be sure that You are an adult", subTitle: "Enter the third letter of word: HAPPY")
}
}
func parentalGatefunctions(){
// Parental gate functions are overriten in classes where they are used for
}
}
下面的子类:
class B: A {
@IBAction func unlockAllCategoriesBtnPressed(_ sender: Any) {
A().parentalGate()
}
override func parentalGatefunctions() {
print ("Do something in class B")
}
}
另一个类:
class C: A {
@IBAction func unlockAllCategoriesBtnPressed(_ sender: Any) {
A().parentalGate()
}
override func parentalGatefunctions() {
print ("Do something in class C")
}
}
在类 B 和 C 中调用 parentalGate() 方法时,始终只调用空的 parentalGateFunctions() 而不会在类中调用覆盖方法。
我做错了什么吗?我只是想避免在我的类(class)中重复代码。
谢谢!
最佳答案
你的错误就在这里。
@IBAction func unlockAllCategoriesBtnPressed(_ sender: Any) {
A().parentalGate()
}
因为您已经对 A
进行了子类化,所以您可以使用该方法。所以,只需调用子类中的方法,而不是父类(super class)的新实例中的方法! (这显然会调用空方法)
@IBAction func unlockAllCategoriesBtnPressed(_ sender: Any) {
parentalGate()
}
关于ios - 重写方法未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53815893/