从文本字段在 tableView 中添加新单元格
Add new cell in tableView from textfield
我创建了一个 table 和一个文本字段。我希望 table 每次用户在文本 box.I 中写入内容时都创建一个新单元格有这样的代码。我为名称创建了一个数组并尝试用它填充单元格,但到目前为止还没有结果。
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
}
如果你想在按下键盘上的 return 键时执行你的操作,你应该实现 UITextfieldDelegate 方法并将键盘委托设置给你的控制器并在这个方法中做一些事情
在您的 viewDidLoad 方法中:
textfield.delegate = self
然后实现委托方法:
extension YourviewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool { //delegate method
let name = addplayerTextFiedOutlet.text!
playerName.append(name)
addplayerTextFiedOutlet.resignFirstResponder()
playerListTableView.reloadData()
return true
}
}
我创建了一个 table 和一个文本字段。我希望 table 每次用户在文本 box.I 中写入内容时都创建一个新单元格有这样的代码。我为名称创建了一个数组并尝试用它填充单元格,但到目前为止还没有结果。
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
}
如果你想在按下键盘上的 return 键时执行你的操作,你应该实现 UITextfieldDelegate 方法并将键盘委托设置给你的控制器并在这个方法中做一些事情
在您的 viewDidLoad 方法中:
textfield.delegate = self
然后实现委托方法:
extension YourviewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool { //delegate method
let name = addplayerTextFiedOutlet.text!
playerName.append(name)
addplayerTextFiedOutlet.resignFirstResponder()
playerListTableView.reloadData()
return true
}
}