我想了解实现委托出UIViewController类的最佳方法是什么
如何使用AuthManager中函数的AuthManager参数管理委托?
这是我工作的两个班..。我给你举一些小例子,让你明白
class StartController: UIViewController {
@objc private func presentAuthFacebookController() {
AuthManager.signInWithFacebook(controller: self)
}
}class AuthManager {
static func signInWithFacebook(controller: UIViewController) {
let loginManager = LoginManager()
loginManager.logIn(permissions: [.publicProfile, .email], viewController: controller) { (result) in
switch result {
case .cancelled : print("\n AuthFacebook: operazione annullata dall'utente \n")
case .failed(let error) : print("\n AuthFacebook: \(error) \n")
case .success(granted: _, declined: let declinedPermission, token: _):
let authVC = ExistingEmailController()
authVC.delegate = // ?????? (controller)
UIApplication.shared.windows.first?.rootViewController?.present(authVC, animated: true, completion: nil)
}
}
}
}发布于 2020-03-22 12:50:44
我个人认为StartController不应该知道/遵守ExistingEmailControllerDelegate。但是,如果确实需要,可以将controller声明为组合类型:
static func signInWithFacebook(controller: UIViewController & ExistingEmailControllerDelegate) {
...
authVC.delegate = controller在我看来,拥有AuthManager的全部意义是在ExistingEmailController之上创建抽象层,并封装身份验证的逻辑。因此,StartController不应该知道,也不应该关心ExistingEmailControllerDelegate。它只知道AuthManager。
AuthManager应该是ExistingEmailController的委托,这意味着signInWithFacebook不应该是静态的,AuthManager可以有一个StartController符合的AuthManagerDelegate:
class AuthManager : ExistingEmailControllerDelegate {
weak var delegate: AuthManagerDelegate?
func signInWithFacebook(controller: UIViewController) {
...
let authVC = ExistingEmailController()
authVC.delegate = self
UIApplication.shared.windows.first?.rootViewController?.present(authVC, animated: true, completion: nil)
}
func someMethodFromExistingEmailControllerDelegate() {
delegate?.someMethod() // delegating it self.delegate, which StartController conforms to
}
}
protocol AuthManagerDelegate : class {
func someMethod()
}
class StartController: UIViewController, AuthManagerDelegate {
var authManager: AuthManager!
override func viewDidLoad() {
authManager = AuthManager()
authManager.delegate = self
}
@objc private func presentAuthFacebookController() {
authManager.signInWithFacebook(controller: self)
}
func someMethod() {
// write here the code that you would have written in someMethodFromExistingEmailControllerDelegate
}
}https://stackoverflow.com/questions/60799303
复制相似问题