当ViewController可能实现或未实现协议时,在UIViewController的viewDidLoad上调用协议函数

时间:2019-01-21 15:44:20

标签: ios swift swift-protocols

仅当当前UIViewController实现该协议独立于我继承的Base类时,我才希望能够在viewDidLoad上调用协议方法。我正在使用下面的Playground代码来说明当前的位置,它调用了该函数,但由于发生EXC_BAD_ACCESS (code=1, address=0x0).错误而崩溃,仅此而已。

import UIKit

protocol AccessibleProtocol where Self: UIViewController {
    func applyAccessibility()
}

class BaseViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        (self as? AccessibleProtocol)?.applyAccessibility()
    }
}

class LoginViewController: BaseViewController {
    var passwordTextField: UITextField!
    override func viewDidLoad() {
        passwordTextField = UITextField()
        super.viewDidLoad()
    }
}

extension LoginViewController: AccessibleProtocol {
    func applyAccessibility() {
        self.passwordTextField.accessibilityLabel = "Enter Password"
    }
}

let loginViewController = LoginViewController()
loginViewController.viewDidLoad()

1 个答案:

答案 0 :(得分:0)

您可以做的是使协议(的种类)功能为可选。

import UIKit

protocol AccessibleProtocol where Self: UIViewController {
    func applyAccessibility()
}

extension AccessibleProtocol {
    func applyAccessibility() {}
}

class BaseViewController: UIViewController, AccessibleProtocol {
    override func viewDidLoad() {
        super.viewDidLoad()
        applyAccessibility()
    }
}

class LoginViewController: BaseViewController {
    var passwordTextField: UITextField!
    override func viewDidLoad() {
        passwordTextField = UITextField()
        super.viewDidLoad()
    }
}

extension LoginViewController {
    func applyAccessibility() {
        self.passwordTextField.accessibilityLabel = "Enter Password"
    }
}

let loginViewController = LoginViewController()
loginViewController.viewDidLoad()

这样,您可以始终从协议中调用de func。而且,如果您没有实现它,它什么也不会做。