skip to Main Content

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 …

2

Answers


  1. 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

    Login or Signup to reply.
  2. to layout the header properly I use the following code in my viewController

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()   
        if let headerView = tableView.tableHeaderView {
    
        let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        var headerFrame = headerView.frame
    
        //Comparison necessary to avoid infinite loop
        if height != headerFrame.size.height {
            headerFrame.size.height = height
            headerView.frame = headerFrame
            tableView.tableHeaderView = headerView
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search