我有一个无法覆盖功能的问题。
我的父母在下面的课:
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()方法时,仅在类中不调用不带overriten方法的空parentalGateFunctions()。
我做错什么了吗?我只是想避免在我的课堂上重复代码。
谢谢!
答案 0 :(得分:4)
您的错误在这里。
@IBAction func unlockAllCategoriesBtnPressed(_ sender: Any) {
A().parentalGate()
}
由于您已经继承了A
,因此可以使用该方法。因此,只需在您的子类中调用该方法,而不是在超类的新实例中调用该方法即可! (显然会调用空方法)
@IBAction func unlockAllCategoriesBtnPressed(_ sender: Any) {
parentalGate()
}