The concept of Custom Delegation is always quite tricky when encountering it for the first time. In today's lesson, we'll go through how to create our first Protocol to implement our finishLoggingIn method.
We'll then go on to conforming to this protocol and performing the custom delegation action when clicking on the login button.
!codebreak
<div class='filename'>LoginControllerDelegate.swift</div>
!codebreak
!syntax-highlight
protocol LoginControllerDelegate: class {
func finishLoggingIn()
}
filebreak:LoginController
class LoginController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, LoginControllerDelegate {
//...
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// we're rendering our last login cell
if indexPath.item == pages.count {
let loginCell = collectionView.dequeueReusableCell(withReuseIdentifier: loginCellId, for: indexPath) as! LoginCell
loginCell.delegate = self
return loginCell
}
//...
}
func finishLoggingIn() {
//we'll perhaps implement the home controller a little later
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
guard let mainNavigationController = rootViewController as? MainNavigationController else { return }
mainNavigationController.viewControllers = [HomeController()]
dismiss(animated: true, completion: nil)
}
//...
}
!codebreak
<div class='filename'>LoginCell.swift</div>
!codebreak
!syntax-highlight
class LoginCell: UICollectionViewCell {
//...
lazy var loginButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .orange
button.setTitle("Log in", for: .normal)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(handleLogin), for: .touchUpInside)
return button
}()
weak var delegate: LoginControllerDelegate?
func handleLogin() {
delegate?.finishLoggingIn()
}
//...
}