Home > Enterprise >  How to solve the problem with headerView in lifecycle
How to solve the problem with headerView in lifecycle

Time:01-11

In my application, depending on whether the user is logged in, header looks differently. The problem is that by calling it in viewDidLoad - it loads incorrectly. Here's my header code:

func configureUITableViewHeader() {
    let header = HomeTableHeaderView.fromNib()
    header.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 200)
    header.backgroundColor = AppColors.mainThemeColor.withAlphaComponent(0.3)
    let bottomLine = UIView(frame: CGRect(x:0, y: header.frame.height, width:header.frame.width , height:3))
    bottomLine.backgroundColor = AppColors.detailsColor
    header.addSubview(bottomLine)
    
    switch UserAccount.shared.state {
        
    case .verified:
        header.configure(delegate: self, labeltext: "Добро пожаловать! \(String(describing: UserAccount.shared.userEmail!))")
        header.logOutButtonUotlet.isHidden = false
        header.logInButtonOutlet.isHidden = true
        tableView.tableHeaderView = header
        
    case .nonVerified:
        header.configure(delegate: self, labeltext: "Пожалуйста, авторизуйтесь чтобы продолжить")
        header.logInButtonOutlet.isHidden = false
        header.logOutButtonUotlet.isHidden = true
        tableView.tableHeaderView = header
        
    default :
        print("nothing to showing")
    }
}

If I call it in ViewDidLoad: enter image description here

If i call it in ViewDidAppear: enter image description here

What could be the problem? I thought I was familiar enough with the controller lifecycle, but ...

CodePudding user response:

viewDidLoad is called when the view is loaded into the memory. Note: The view is not completely rendered at this point of time hence, you will not get the exact size of the parent view or the window.

viewDidAppear is called when the view is added to the view hierarchy. Here, the view rendering is complete. This is where you will get the correct size of it's parent view or the window.

https://developer.apple.com/documentation/uikit/uiviewcontroller/1621423-viewdidappear

CodePudding user response:

надо учитывать layoutSubviews. Вызывается после viewDidLoad()

layoutSubviews вызывается, когда представление уже знает свои размеры, поэтому, вызвав все во viewDidLoad представление обновляется без учета отработанного кода. ваш код можно поместить внутри layoutSubviews(), тогда не придется думать, когда и где вызвать его.

  •  Tags:  
  • Related