在UITableViewCell中进行内联编辑?

时间:2020-09-24 19:40:38

标签: ios swift

我正在尝试构建一个使用UITableView和UITableView Cell的应用程序。

我希望用户点击“添加”按钮将项目添加到TableView中,而无需调用新窗口或警报弹出窗口。我还希望用户点击一个单元格来编辑其值,然后保存它。

我正在努力寻找最佳方法。根据Apple关于UITableViewCell的文件记录,似乎不太可能。

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

这是一个非常基本的例子。

在情节提要中,添加嵌入UITableViewController中的UINavigationController。将表视图控制器的“自定义类”设置为SampleTableViewController。这就是您运行此程序所需要做的全部。

该表开始为空。点击导航栏上的添加(“ +”)按钮,将新项目添加到数据数组并重新加载表。

在编辑文本字段时,文本将通过“回调”闭包传递回控制器,在此我们使用新字符串更新数据数组。

还有一个“完成”按钮-点击它会简单地将数据数组print移至调试控制台,以便我们可以看到更改。在那您可以进行一些操作,例如保存用户输入的数据(或您打算使用该数据进行的其他任何操作)。


SampleTableViewController类

class SampleTableViewController: UITableViewController {
    
    var myData: [String] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // cells will have text fields, so we want to be able to
        //  dismiss the keyboard by scrolling the table
        tableView.keyboardDismissMode = .onDrag
        // register our custom cell
        tableView.register(SampleTextFieldCell.self, forCellReuseIdentifier: "cell")
        // put system Add "+" button and system "Done" button
        //  on right side of the navigation bar
        let addBtn = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(self.addButtonTapped))
        let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.doneButtonTapped))
        navigationItem.rightBarButtonItems = [doneBtn, addBtn]
    }
    @objc func addButtonTapped() -> Void {
        // add a new element to data array
        myData.append("")
        // reload the table
        tableView.reloadData()
    }
    @objc func doneButtonTapped() -> Void {
        // do something with the added / edited items
        //  maybe save then to a database?
        // for now, just print the data array to the debug console
        print(myData)
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myData.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SampleTextFieldCell
        cell.theTextField.text = myData[indexPath.row]
        // set the "callback" closure so we can save the text as its being edited
        cell.callback = { str in
            // update data array when text in cell is edited
            self.myData[indexPath.row] = str
        }
        return cell
    }
}

SampleTextFieldCell类

class SampleTextFieldCell: UITableViewCell {
    
    let theTextField = UITextField()
    
    // closure used to tell the controller that the text field has been edited
    var callback: ((String) ->())?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        theTextField.borderStyle = .roundedRect
        theTextField.placeholder = "Enter new item..."
        theTextField.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(theTextField)
        let g = contentView.layoutMarginsGuide
        NSLayoutConstraint.activate([
            theTextField.topAnchor.constraint(equalTo: g.topAnchor, constant: 0.0),
            theTextField.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 0.0),
            theTextField.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: 0.0),
            theTextField.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: 0.0),
        ])
        theTextField.addTarget(self, action: #selector(self.textFieldEdited(_:)), for: .editingChanged)
    }
    @objc func textFieldEdited(_ textField: UITextField) -> Void {
        // send newly edited text back to the controller
        callback?(textField.text ?? "")
    }
}
相关问题