Creating reusable FooterView for different TableViews (Swift 5)

I created class FooterView: UIView. I use it to create FooterView for my TableView. But also I’d like to reuse this class to create FooterView in my other TableViews. When I try to add an argument to the setupElements () function to pass the required TableView there and change the Label text depending on it, but the initializer does not allow me to do this. How can i do this? Also, Swift doesn’t allow me to directly call the setupElements () function even when I remove the "private". My code:

class FooterView: UIView {      private var footerLabel: UILabel = {         ...     }()      private func setupElements() {         addSubview(footerLabel)         ...         footerLabel.text = "Table is empty"     }          override init(frame: CGRect) {         super.init(frame: frame)         setupElements()     }          required init?(coder: NSCoder) {         fatalError("init(coder:) has not been implemented")     } } ... class TableViewController: UIViewController {    private lazy var footerView = FooterView()    private var array: [String] = []     func viewDidLoad() {       super.viewDidLoad()       setupTableView()    }     private func setupTableView() {       tableView.register(UINib(nibName: "Cell", bundle: nil), forCellReuseIdentifier: LibraryCell.reuseId)       if array.count == 0 {          tableView.tableFooterView = footerView       }    } }  extension TableViewController: UITableViewDelegate, UITableViewDataSource {...} 
Add Comment
1 Answer(s)

After a lot of searching, I solved my problem. I removed the initialization and create a FooterView through the setupFooterView function (for vc: UIViewController) into which I pass the ViewController I need as a parameter. The code looks like this:

class FooterView: UIView {     private var footerLabel: UILabel = {         let label = UILabel()         ...         return label     }()      func setupFooterView(for vc: UIViewController) -> UIView {         let footerView = UIView()         footerView.addSubview(footerLabel)         ...         if vc is TableViewController {         footerLabel.text = "..."         } else if vc is SecondTableViewController {             footerLabel.text = "..."         }         return footerView     } } 

Adding FooterView to the ViewController I need:

... private lazy var footerView = FooterView() ... tableView.tableFooterView = footerView.setupFooterView(for: self) 
Answered on August 31, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.