【问题标题】:Add new cell in tableView from textfield从文本字段在 tableView 中添加新单元格
【发布时间】:2020-05-23 19:57:27
【问题描述】:

我创建了一个表格和一个文本字段。每次用户在文本框中写东西时,我希望表格创建一个新单元格。我有这样的代码。我为名称创建了一个数组并尝试用它填充单元格,但到目前为止还没有结果。

var playerName = [String]()
    @IBAction func addPlayerNameTextFieldAction(_ sender:UITextField)
    {

        let name = addplayerTextFiedOutlet.text!
        playerName.append(name)

        addplayerTextFiedOutlet.resignFirstResponder()
        playerListTableView.reloadData()
    }




func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = playerListTableView.dequeueReusableCell(withIdentifier: idCell, for:indexPath) as! PlayerListTableViewCell
            cell.playerNameLabel.text =  playerName[indexPath.row]

        return cell
}

【问题讨论】:

  • no result是什么意思?
  • 我在文本字段中输入单词,按回车键,没有任何操作。连键盘都没有消失。
  • 是否调用了该操作?请使用调试器。
  • 点击文本字段后,出现一个键盘,我可以输入文本,但接下来没有任何反应。我试图将数组输出为字符串,但它没有输出任何内容

标签: ios arrays swift uitableview uitextfield


【解决方案1】:

如果您想在键盘上按回车键时执行您的操作,您应该实现 UITextfieldDelegate 方法并将键盘委托设置为您的控制器并在此方法中执行操作

在你的 viewDidLoad 方法中:

textfield.delegate = self

然后 impelement 委托方法:

extension YourviewController: UITextFieldDelegate {

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
   let name = addplayerTextFiedOutlet.text!
        playerName.append(name)
        addplayerTextFiedOutlet.resignFirstResponder()
        playerListTableView.reloadData()
        return true
 }
}

【讨论】:

  • 谢谢,但不幸的是这对我不起作用。它仍然没有响应 Return
  • 您是否设置了文本字段委托?首先你应该让你的 viewController 符合 UITextfieldDelegate 然后将你的文本字段委托设置为 viewcontroller 然后这个方法应该可以工作
  • 一开始我加了一个delegate,但是没用,后来我通过扩展做了,一切都很好。谢谢你这么笨!
猜你喜欢
  • 1970-01-01
  • 2020-10-20
  • 2016-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-17
  • 1970-01-01
相关资源
最近更新 更多