Skip to main content

How to Use Multiple Sections in UITableView iOS Swift !

Multiple sections in UITableView iOS Swift.

UITableView is very important part of iOS ecosystem. So we split tableviews in sections. Then its easier to find right information. 


Multiple Sections in UITableView iOS Swift 5


1. First let’s create a project as usual. Create a new single view application X code project. Set project name to UIViewController. 

2. Go to main storyboard & select view controller & use UITableView

3. Select tableview & make it initial view controller 

4 Create a custom Sections Class like Name => TableSections, create register cell static return getCellNibsmethod. Then create  4 section enum “TableItems” then after append all sections to an array model.


import UIKit

struct CellNib{

    static func getCellNibs() -> [String] {

        return ["Cell1","Cell2","Cell3","Cell4"]

    }

}

enum TableItems: Int {

    case TableSections1

    case TableSections2

    case TableSections3

    case TableSections4

}

class TableSections: NSObject {

    var sectionType : TableItems?

    init(tItems:TableItems) {

        sectionType = tItems

    }

class func sectionsForTable()->[TableSections] {

        var sections = [TableSections]()

        sections.append(TableSections(tItems: TableItems.TableSections1))

        sections.append(TableSections(tItems: TableItems.TableSections2))

        sections.append(TableSections(tItems: TableItems.TableSections3))

        sections.append(TableSections(tItems: TableItems.TableSections4))

        return sections

}

}

5. After Create a custom 4 UITableViewCell with xib. Cell1, Cell2, Cell3, Cell4.


import UIKit

class Cell1: UITableViewCell {

    override func awakeFromNib() {

        super.awakeFromNib()

        // Initialization code

    }

    override func setSelected(_ selected: Bool, animated: Bool) {

        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state

    } 

}

Same Cell2, Cell3, Cell4

6. After Create a TableCommonVC UIViewController and UITableViewDelegate, UITableViewDataSource, setup section, and register table cells.


import UIKit

class TableCommonVC: UIViewController, UITableViewDelegate, UITableViewDataSource{

    var tSections: [TableSections]?

    @IBOutlet weak var tlbView : UITableView!

    override func viewDidLoad() {

        super.viewDidLoad()

        self.setupSection()

        self.setTlbNibs()

        self.tlbView.reloadData()

    }

    func setTlbNibs(){

        for item in CellNib.getCellNibs() {

            let nib = UINib(nibName: item , bundle: nil)

            self.tlbView.register(nib, forCellReuseIdentifier: item)

        }

    }

    func setupSection(){

        self.tSections = TableSections.sectionsForTable()

    }

    //MARK: UITableView Delegate & DataSource

    func numberOfSections(in tableView: UITableView) -> Int {

        return (self.tSections != nil) ? self.tSections!.count:0

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return setRows(tItems: self.tSections![section].sectionType!)

    }

    func setRows(tItems: TableItems)->Int {

        switch tItems {

            case .TableSections1:return getS1RowCount()

            case .TableSections2:return getS2RowCount()

            case .TableSections3:return getS3RowCount()

            case .TableSections4:return getS4RowCount()

        }

    }

    func getS1RowCount()->Int{ return 0 }

    func getS2RowCount()->Int{ return 0 }

    func getS3RowCount()->Int{ return 0 }

    func getS4RowCount()->Int{ return 0 }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        return setCells(indexPath: indexPath)!

    }

    func setCells(indexPath: IndexPath)-> UITableViewCell? {

        let tItem = tSections![indexPath.section]

        switch tItem.sectionType! {

        case .TableSections1:return getCellS1(indexPath: indexPath)

        case .TableSections2:return getCellS2(indexPath: indexPath)

        case .TableSections3:return getCellS3(indexPath: indexPath)

        case .TableSections4:return getCellS4(indexPath: indexPath)

        }

    }

    func getCellS1(indexPath:IndexPath)->UITableViewCell?{ return nil }

    func getCellS2(indexPath:IndexPath)->UITableViewCell?{ return nil }

    func getCellS3(indexPath:IndexPath)->UITableViewCell?{ return nil }

    func getCellS4(indexPath:IndexPath)->UITableViewCell?{ return nil }

}


7. Now Create a TableSectionDemoVC for visibility tableview and override UITableView numberOfRowsInSection and  cellForRowAt methods.

import UIKit

class TableSectionDemoVC: TableCommonVC{

    override func viewDidLoad() {

        super.viewDidLoad()

        self.setTlbNibs()

        self.tlbView.reloadData()

    }

    override func getS1RowCount()->Int{ return 1 }

    override func getS2RowCount()->Int{ return 1 }

    override func getS3RowCount()->Int{ return 1 }

    override func getS4RowCount()->Int{ return 1 }

    

    override func getCellS1(indexPath:IndexPath)->UITableViewCell?{

        if let hCell = self.tlbView.dequeueReusableCell(withIdentifier: "Cell1") as? Cell1{

            hCell.selectionStyle = .none

            return hCell

        }

        return nil

    }

    override func getCellS2(indexPath:IndexPath)->UITableViewCell?{

        if let hCell = self.tlbView.dequeueReusableCell(withIdentifier: "Cell2") as? Cell2{

            hCell.selectionStyle = .none

            return hCell

        }

        return nil

    }

    override func getCellS3(indexPath:IndexPath)->UITableViewCell?{

        if let hCell = self.tlbView.dequeueReusableCell(withIdentifier: "Cell3") as? Cell3{

            hCell.selectionStyle = .none

            return hCell

        }

        return nil

    }

    override func getCellS4(indexPath:IndexPath)->UITableViewCell?{

        if let hCell = self.tlbView.dequeueReusableCell(withIdentifier: "Cell4") as? Cell4{

            hCell.selectionStyle = .none

            return hCell

        }

        return nil

    }

}

 

Overview

Table views in iOS display rows of vertically scrolling content in a single column. Each row in the table contains one piece of your app’s content.
For example, the Contacts app displays the name of each contact in a separate row, and the main page of the Settings app displays the available groups of settings.
You can configure a table to display a single long list of rows, or you can group related rows into sections to make navigating the content easier. :- https://developer.apple.com/documentation/uikit/uitableview

How to Create UITableView with multiple sections in iOS ,Binding a list with multiple sections and different cells,Build Sections With Nested Types UITableView,UITableView with multiple sections swift 5 ,Dynamic sections UITableView example swift 5,UITableView swift uitableview style grouped programmatically swift ,Set section in uitableview swift


Comments

  1. How to Use Multiple Sections in UITableView iOS Swift !

    Very interesting post...!

    Well, we are here to share our ecommerce app development company

    ecommerce app development services

    Waiting for your future posts....


    ReplyDelete

Post a Comment

Popular posts from this blog

How Create Animated Circle Progress Bar iOS 11 Swift 4

  Animated Circle Progress Bar iOS 11 Swift 4 With MBCircularProgressBa r - https://github.com/MatiBot/MBCircularProgressBar A circular, animatable & highly customizable progress bar from the Interface Builder Swift, Using pod fite MBCircularProgressBar Installation Cocoapods terminal. pod "MBCircularProgressBar" That - A Simple Steps to installed pod file -        Open terminal        Command on terminal go to project folder Cd path        set your project path on terminal.        command : pod init        open pod file - open -e podfile        added in pod file with in : pod "MBCircularProgressBar"        Command : Pod install        Close project of Xcode        open your Project from terminals        Command : open PodDemos.xcworkspace After opern StoryBoard and Now drag a UIView over the viewController in storyboard Or set UIView Constraint width, height or verticle or horzentail space and set a class MBCircul

Add a Scene Delegate to your existing project with Storyboard in Swift

To add a scene delegate, first, create a new Swift file that you’ll call "SceneDelegate" containing a subclass of UIResponder, just like the AppDelegate, and that conforms to UIWindowSceneDelegate.  As your app might supports other versions than iOS 13, make this class only available for iOS 13. This is what you should have : If you are working a project that is storyboard based, please set storyboard  initial view controller SceneDelegate.swift import UIKit @available ( iOS 13.0 , *) class SceneDelegate : UIResponder , UIWindowSceneDelegate {     var window : UIWindow ?     func scene ( _ scene: UIScene , willConnectTo session: UISceneSession , options connectionOptions: UIScene . ConnectionOptions ) {                  let storyboard = UIStoryboard (name: "Main" , bundle: nil )         let initialViewController = storyboard. instantiateViewController (withIdentifier: "ViewController" )         let mainNavigationController = UINavigationControlle