Swift中:如何用文本字段的内容填充下一个可用的表视图单元格



我有一个ViewController.swift和一个TableViewCell.swift文件。在主情节提要中,我有一个基本的视图控制器,顶部有一个文本字段,下面有一个表视图。我在表视图中有一个原型单元格,它的标识符是"单元格",类是"TableViewCell"。

我希望用户点击文本字段,输入字符串,然后单击键盘上的返回。然后,我希望将该字符串粘贴到下一个可用的表视图单元格中(每次发生这种情况时,下一个较低的单元格应该填充(。

除了文件已经有的基本代码之外,我还有以下内容:

在ViewController.swift:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var tableView: UITableView!
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
 let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
    let textFromField = textField.text
    cell.textLabel!.text = textFromField
    return cell }

您需要一个字符串数组变量

var array = [String]

然后,您需要将文本字段的文本值附加到数组

array.append(textField.text)

然后,在您的数据源中,您需要返回区段的数量(在您的情况下似乎是1(和区段中的行数

array.count

然后在cellForRowAtIndexPath中,您需要返回数组中的每个项

let item = array[indexPath.row]
cell.textLabel.text = item
return cell

据我所知。您应该使用delegate

  1. 通过要填充的indexPath.row计算rowWillFill
  2. TableViewCell实现委托。

    if(cell_index=indexPath.row({

    rowWillFill += 1
    tableViewCell.textLabel.text = String
    

    }

  3. 然后通过tableView.updateCellAtIndexPath更新单元格好运!

最新更新