I'm trying to use delegate and protocol first time.
I want to change the theme across many view controller.
Then on any controller which has protocol to change theme
When I go to this controller now I expect theme to be new but is old.
I do not go from theme controller to where them has changed
My code
protocol ThemeDelegate: class {
func changeTheme(theme: UIColor)
}
class FirstController: UICollectionViewController, UICollectionViewDelegateFlowLayout, ThemeDelegate {
var newTheme: UIColor = .red
func changeTheme(theme: UIColor) {
newTheme = theme
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = newTheme
}
}
ThemeController {
weak var themeDelegate: ThemeDelegate?
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let theme = .blue
themeDelegate?.changeTheme(theme: theme)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: themeCellId, for: indexPath) as! ThemeCell
cell.themeImageView.image = UIImage(named: "theme cell image")
return cell
}
}
I'll try to make it simple:-
1) First, declare a protocol:-
2) Have a variable of that protocol in your ThemeController:
3) Call the delegate functions through
themeDelegate
:- (you've done this right till this step)4) You need to conform your
AnyController
as the delegate, likeyourThemeControllerInstance.delegate = self
and you've done that as well.It doesn't work because you've declared a new instance of
ThemeController
and have conformedAnyController
to be the delegate of that new instance which supposedly has the same old theme:In order for your delegate to work as expected, you need the same instance of
ThemeController
where you change your themeYou can set delegate but careful view needs a be load.
You do this also with notifications and send all viewControllers with conforms Theme
1 - Your Step
2 - Observer Step
Have Fun!