我有一个应用程序,其中包含一个中央视图控制器,在滚动视图中有3个子视图控制器,代表应用程序的各个部分。我的应用程序的一般流程如下
LoginVC -> AppVC [Settings, Inbox, Email]
我目前在我的设置视图控制器中有我的注销按钮,但实际的注销功能需要在AppVC中。我试过实现一个委托,但似乎无法让它正常工作
class Settings: UIViewController {
var delegate: LogoutDelegate?
@IBAction func logout(_ sender: Any) {
delegate?.logoutOfApp()
}
}
protocol LogoutDelegate: class {
func logoutOfApp()
}
----------------------------------
class AppVC: UIViewController, LogoutDelegate {
func logoutOfApp() {
print("This should be called")
//Execute logout code
}
}
任何人都可以帮我弄清楚为什么我的委托功能没有在我的AppVC中调用吗?
更新
这是我在滚动视图中设置子视图控制器的方法
func setupViews() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let settingsVC = storyboard.instantiateViewController(withIdentifier: "SettingsVC")
let inboxVC = storyboard.instantiateViewController(withIdentifier: "InboxVC")
let emailVC = storyboard.instantiateViewController(withIdentifier: "EmailVC")
let viewControllers = [settingsVC, inboxVC, emailVC]
let width = scrollView.bounds.width
let height = scrollView.bounds.height
scrollView.contentSize = CGSize(width: width * 3, height: height)
var idx = 0
for vc in viewControllers {
addChildViewController(vc)
let originX = CGFloat(idx) * width
vc.view.frame = CGRect(x: originX, y: 0, width: width, height: height)
scrollView.addSubview(vc.view)
vc.didMove(toParentViewController: self)
idx += 1
}
scrollView.setContentOffset(CGPoint(x: width, y: 0), animated: false)
}
我不知道在哪里设置我的代表。我试图在我的for循环self.delegate = vc
中设置它,但总是得到相同的错误,无法设置委托
答案 0 :(得分:0)
问题是您从未设置委托,否则委托将始终为nil
且delegate?.logoutOfApp()
将不会被执行。
在AppVC
中,您需要执行以下操作:
override func viewDidLoad() {
super.viewDidLoad()
settings.delegate = self
}