Search code examples
iosswiftuitableviewtableview

How to create dynamic section in table view swift based on the user input?


I'm trying to create a number of sections based on the input from the user in the text field. take a look at my snapshot to make it easier.

enter image description here

as default, I created 1 section of label 1, label 2, label 3, label 4. but if the number of section text field is inputed 3, I want the section that fills with labels to increase into 3. How do I do that? My problem is that it does not add up another section when I type it. I had also put tableView.reloadData() in some possible places but it didn't work. Here's my code, any suggestion will be appreciated.

Thankyou in advance.

var numberOfSection: String = "0"

override func viewDidLoad() {
    super.viewDidLoad()
}

override func numberOfSections(in tableView: UITableView) -> Int {
    if numberOfSection == "0" {
        return 2
    }
    
    else if numberOfSection == "1" {
        return 2
    }
    
    else {
        print(numberOfSection)
        return Int(numberOfSection) ?? 2
    }
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    switch section {
    case 0:
        return 1
    case 1:
        return WSSpec.count
    default:
        return 0
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    switch indexPath.section {
    case 0:
        let cells = tableView.dequeueReusableCell(withIdentifier: "serverNumbCell", for: indexPath) as! CellOutlet
        let txtFieldServerNumber = cells.txtFieldServerNumb
        cells.lblSectionNumb.text = "Number of section:"
        txtFieldServerNumber?.addTarget(self, action: #selector(sectionTxtFieldDidChange), for: .editingChanged)
        return cells
    case 1:
        let cells = tableView.dequeueReusableCell(withIdentifier: "serverSpecCell", for: indexPath) as! CellOutlet
        let specWS = testSpec[indexPath.row]
        cells.labels.text = specWS.spec
        return cells
    default:
        return CellOutlet()
    }
}

@objc func sectionTxtFieldDidChange(_ sender: UITextField) {
    numberOfSection = sender.text ?? "2"
}

Solution

  • Try adding a didSet to the variable then reloading data from there. Like this:

    var numberOfSection: String = "0" {
      didSet {
        tableView.reloadData()
      }
    }