iosswiftuitableviewuitableviewsectionheaderuitableviewautomaticdimension

Is it possible to achieve expandable table header view?


I have implemented table view with expandable section i.e. the section user choose will have number of items for that particular category. For closed section there will be 0 items.

Now for better UI purpose, I want to achieve following type of table view which has expandable header view? In this image, we can see that section looks like a group with items it contains with rounded corners and border. As per default UITableView, this behavior is not possible. Still if any one has implemented, please give some advise whether it is feasible or not.

enter image description here


Solution

  • struct WrapperObject {
        var header : HeaderObject
        var listObject : [ObjectDetail]
    }
    
    struct HeaderObject {
        var id : String
        var isOpen : Bool
    }
    
    struct ObjectDetail {
        var id : String
        var detailInfo : String
    }
    

    In your VC or datasource. Create : private var internalData : [WrapperObject]

    After set data, in the delegate of UITableView

    extension ViewController : UITableViewDelegate {
        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
                // TODO : Custom your own view
                // have a callback to set property isOpen =  true or false to the internalData.
                return UIView()
            }
        }
    
    extension ViewController : UITableViewDataSource {
    
            func numberOfSections(in tableView: UITableView) -> Int {
                return internalData.count
            }
    
            func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                if internalData[section].header.isOpen {
                    return internalData[section].listObject.count
                } else {
                    return 0
                }
    
            }
    
            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                return UITableViewCell() // TODO: custom your own cell
            }
        }