如何根据用户输入在 table 视图 swift 中创建动态部分?

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

我正在尝试根据用户在文本字段中的输入创建多个部分。 看看我的快照,让它更容易。

默认情况下,我创建了标签 1、标签 2、标签 3、标签 4 的 1 个部分。 但是如果节文本字段的数量输入 3,我希望填充标签的节增加到 3。 我怎么做? 我的问题是,当我输入它时,它不会添加另一个部分。 我也把 tableView.reloadData() 放在一些可能的地方,但它没有用。 这是我的代码,如有任何建议,我们将不胜感激。

提前谢谢你。

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"
}

尝试向变量添加一个 didSet,然后从那里重新加载数据。像这样:

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