How to deal with dynamic Sections and Rows in iOS UITableView

后端 未结 3 1642
深忆病人
深忆病人 2020-12-10 21:07

My issue

When I deal with UITableView, I basically have an Array table_data with my sections and rows.



        
相关标签:
3条回答
  • 2020-12-10 21:41

    It is a bad practice to use NSDictionary for storing data. Create new class for section (i.e. SectionData) and row (i.e. RowData). Your ViewController (or some other data provider) will keep array of SectionData, where SectionData keeps array of RowData. RowData may contain func for handling row selection, so in didSelectRowAtindexPath you just do something like this:

    let rowData = rowDataAtIndexPath(indexPath)
    rowData.tapHandler()
    

    where rowDataAtIndexPath is your defined function that gives you data for indexPath.

    When you need to remove some section, just remove it from array of sections and reload tableView.

    0 讨论(0)
  • 2020-12-10 21:48

    An approach I use when creating a table where I know all the possible sections is with enums. You create an enum for each of the possible section types:

    enum SectionTypes { case sectionA, sectionB, sectionC }

    And then create a variable to hold the sections:

    var sections: [SectionTypes]

    When you have your data ready then you populate sections with the sections that needs to be displayed. I usually also make a method to help get the section:

    func getSection(forSection: Int) -> SectionTypes {
            return sections[forSection]
        }
    

    With this in place you can start implementing the common DataSource delegate methods:

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return sections.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch getSection(forSection: section) {
        case .sectionA:
            return 0 //Add the code to get the count of rows for this section
        case .sectionB:
            return 0
        default:
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch getSection(forSection: indexPath.section) {
        case .sectionA:
            //Get section A cell type and format as your need
        //etc
        }
    }
    
    0 讨论(0)
  • 2020-12-10 21:51

    I think this talk is broader than what you are seeking but he talks about it.

    https://realm.io/news/altconf-benji-encz-uikit-inside-out-declarative-programming/

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