Search code examples
iosswift3viewdidloadviewdidappear

viewDidLoad vs viewDidAppear - Name Label issues


I'm having this problem regarding the displaying and updating of the username label.

User id 1 - ‘Felicia’

User id 2 - ‘Sam’

(1st screen: default user is 'Felicia') 1st screen: default user is 'Felicia'

(2nd screen: when change user to 'Sam') 2nd screen: when changed user to 'Sam'

(3rd screen: after clicking to another screen, the username's label auto revert back to 'Felicia' when it supposed to be 'Sam') 3rd screen: after clicking to another screen, the username's label auto revert back to 'Felicia' when it supposed to be 'Sam' as user is not changed

My ideal output is that the username's label will stay as the selected user unless user is changed and also to be able to reflect the name label on the side menu bar whenever the name is updated.

In my codes, I tried adding my methods(getUserInfo() and setUserNameLabel()) in viewDidAppear and viewDidLoad, however both scenarios are not generating the output I want.

viewDidAppear

Advantages: - Name label will reflect the update of selected user's name (User can change their name)

Disadvantages: - Name label will revert to the user id 1’s name on side menu bar when selecting other views

viewDidLoad

Advantages: - Name label won’t revert to the user id 1’s name on side menu bar when selecting other views

Disadvantages - Name label won’t reflect the update of selected user's name


Solution

  • work around: what about viewWillAppear or viewWillLayoutsubviews

    I thinks viewWillAppear or viewWillLayoutsubviews (in case you use autolayout) is what you need. When you switch from Felicia to Sam, you must save that state to somewhere to refer when you reopen your side menu.

    pseudocode code:

    var selected = Felicia
    if `Felicia` clicked:
       selected = Felicia
    if `Sam` clicked:
       selected = Sam
    (save selected to somewhere like NSUserDefault)
    

    And in your side menu viewWillAppear: change the UI with selected user.

    load selected (from somewhere like NSUserDefault)

    if selected == `Felicia` 
      do UI update at main thread
    if selected == `Sam`
      do UI update at main thread
    

    Take a look at UIViewController lifecycle:

    enter image description here