Search code examples
iosswiftuitableviewuiviewcontrolleruikit

Passing a variable into custom UITableViewHeaderFooterView


There's a UIViewController containing UITableView.

class ProfileViewController: UIViewController {

    private lazy var profileView: ProfileHeaderView = {
        let profileView = ProfileHeaderView()
        return profileView
    }()
    
    private lazy var feedView: UITableView = {
        let feedView = UITableView().feedView(isHeaderHidden: true)
        feedView.isUserInteractionEnabled = true
        feedView.allowsSelection = true
        return feedView
    }()
...
}

In this UITableView there's a custom header (custom class ProfileHeaderView conforms to protocol UITableViewHeaderFooterView), which is implemented this way:

extension ProfileViewController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            if let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "ProfileHeaderView") as? ProfileHeaderView {
                view.isUserInteractionEnabled = true
                return view
            }
        }
        return nil
    }
}    

Let's say our ProfileHeaderView has a variable (e.g. a string). How to pass the value for this variable from our UIViewController into our custom header?

Edit Here's a quick glance on ProfileHeaderView declaration:

class ProfileHeaderView: UITableViewHeaderFooterView {
        
    public var statusText: String?
    
     override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        addSuviews()
        setupConstraints()
        changeBackgroundColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        addSuviews()
        setupConstraints()
        changeBackgroundColor()
    }
    
    ...
}

Solution

  • Simply assign a value to statusText.

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            if let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "ProfileHeaderView") as? ProfileHeaderView {
                view.isUserInteractionEnabled = true
                view.statusText = "some status text for section 0"
                return view
            }
        }
        return nil
    }
    

    But you also need to have your header view update a label or some other UI component when statusText is changed.

    class ProfileHeaderView: UITableViewHeaderFooterView {
        public var statusText: String? {
            didSet {
                someLabel.text = statusText // update the UI as needed
            }
        }