如何在按钮操作中添加和删除文本字段?

how to add and remove textfield in button action?

我使用的 tableview 方法对我的功能不方便。

功能:当我单击加号按钮时,使用加号按钮创建新的文本字段。但是以前的文本字段加号按钮更改为减号按钮。当我单击减号按钮时,特定文本字段被删除。 如果我尝试使用 tableview,将会出现很多错误。

请帮帮我!我该如何创建此功能!

我不知道这是正确的方法,但你可以得到你想要实现的类似的东西。

在 UITableViewCell 中声明 HomeVC

class TextFieldCell: UITableViewCell {

    var home: HomeVC?

    //Add textfield
    //Add "addDeleteButton" for adding and removing

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        //Add target for "addDeleteButton"
        addDeleteButton.addTarget(self, action:#selector(handleAddDelete), for: .touchUpInside)
    }

    @objc func handleAddDelete() {
        //Pass UITableViewCell as parameter
        home?.update(forCell: self)
    }
}

像下面这样从 cellForRow 分配家庭控制器

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

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! TextFieldCell
    cell.home = self

    if indexPath.row == attractions.count - 1 {
        //Set background image for adding(plus) to addDeleteButton
    } else {
        //Set background image for remove(minus) to addDeleteButton
    }
    return cell
}

为 HomeVCadding/removing 单元格添加此功能

func update(forCell: TextFieldCell) {

    let indexPath = tableView.indexPath(for: forCell)

    if indexPath?.row == attractions.count - 1 {

        //Set background image for remove(minus) to addDeleteButton
        forCell.addDeleteButton.setBackgroundImage(UIImage(named:"minus"), for: .normal)

        attractions.append(attractions[0])
        tableView.beginUpdates()
        tableView.insertRows(at: [[0,attractions.count-1]], with: .automatic)
        tableView.endUpdates()
    } else {
        attractions.remove(at: (indexPath?.row)!)
        tableView.beginUpdates()
        tableView.deleteRows(at: [indexPath!], with: .automatic)
        tableView.endUpdates()
    }
}

输出