UITableView with different optional sections?

前端 未结 1 786
没有蜡笔的小新
没有蜡笔的小新 2021-01-27 02:40

I am looking for a \"good\" way to solve some special requirements:

I have an UITableView with different sections, for example:

  • Base Data
  • About m
1条回答
  •  孤城傲影
    2021-01-27 02:56

    This looks like my way of approaching such problems. I'm using enums (Obj-C & especially Swift) to handle and identify my Sections and I always return the full amount of potential sections:

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return FormSection.count // enum function
    }
    

    In func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int, however, I switch the unused sections off by returning 0 rows.

    The benefit I saw after struggling with your type of dynamic tables was that all sections are always at the same index which made cell management relatively easy:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let section:FormSection = FormSection(rawValue:indexPath.section)!
    
        switch section {
        case .Header:
            //…
        default:
            //…
        }
    }
    

    The same goes for section headers/footers:

    override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case FormSection.Header.rawValue:
            return nil
        case FormSection.RoomSetup.rawValue where foo == false:
            return nil
        default:
            // return header with title = FormSection(rawValue: section)?.headerTitle()
            // Swift enums ftw ;)
        }
    

    And the number of rows is calculated/fetched at runtime:

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let section:FormSection = FormSection(rawValue:section)!
        switch section {
        case .Section1:
            return fooExpanded ? (numberOfFoo) : 0
        case .Section2:
            return model.barCount()
        default:
            return 1
        }
    }
    

    0 讨论(0)
提交回复
热议问题