ios - 重写方法未被调用

标签 ios swift overriding

我遇到了无法覆盖函数的问题。

我的父类如下:

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/

相关文章:

c++ - 我的方法调用是如何解决的?

django - 覆盖 django-allauth 中的模板

iphone - 将通配 rune 件名从主包复制到文档?

iphone - App Store 发布新更新/版本时如何通知用户?

ios - 模态视图 Controller 在 iOS 5.1 中旋转不正确,而不是在 5.0 中

ios - UITableViewDataSource 无法附加到类,swift-ios 中编译错误

java - 为什么如果改变 equals 方法的返回值,输出会改变?

ios - 无法将类型 'NSURL' 的值转换为 'SocketIO.SocketManagerSpec

ios - 当 ctrl + 拖动时,Xcode 不显示完整的 segues 列表

ios - Auth0 Credentials 对象的到期日期属性始终为零