gpt4 book ai didi

ios - 完成编辑单元格内的 TextView 后,将另一个单元格添加到 TableView

转载 作者:行者123 更新时间:2023-11-28 13:54:14 25 4
gpt4 key购买 nike

我想先说明一下我不使用 Storyboard这一事实。

我有一个包含多个部分的 tableview,这些部分充满了我以编程方式创建的 tableViewcell。这些自定义单元格包含一个带有一些占位符文本的文本字段。我希望用户能够做的是点击文本字段,键入他们的条目,然后点击“Enter”关闭键盘,然后在他们刚刚编辑的单元格下方创建一个新单元格。这与提醒应用中发生的行为非常相似。

我很难弄清楚如何访问 tableview 的数据模型(数组)并弄清楚该单元格位于哪个部分,将新字符串添加到数组,然后添加另一个哑单元格有占位符文本。

最佳答案

首先,您必须创建一种在单元格和 View Controller 之间进行通信的方法。您可以为此使用委托(delegate)模式或回调。例如:

final class TextFieldCell: UITableViewCell {

// MARK: - IBOutlets
@IBOutlet weak var textField: UITextField!

// MARK: - Local variables
var callback: ((_ text: String) -> Void)?

// MARK: - Lyfecycle
override func awakeFromNib() {
super.awakeFromNib()
textField.delegate = self
}
}

另外不要忘记调用我们的回调:

extension TextFieldCell: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
callback?(textField.text!)
return true
}
}

太棒了!现在我们将我们的字符串从单元发送到 Controller !

View Controller 的代码示例(简化版):

class ViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet weak var tableView: UITableView!

// MARK: - Local variables
var titles = ["Hello", "world"]
}

// MARK: - UITableViewDataSource

extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let textFieldCell = tableView.dequeueReusableCell(withIdentifier: "textFieldCell", for: indexPath) as! TextFieldCell

textFieldCell.textField.placeholder = titles[indexPath.row]
textFieldCell.callback = { [weak self] newTitle in // don't forget about memory leaks
guard let `self` = self else { return }

// calculating index path for new row
let newIndexPath = IndexPath(row: indexPath.row + 1, section: indexPath.section)

// appending a new row in table view
self.titles.append(newTitle)
self.tableView.insertRows(at: [newIndexPath], with: UITableView.RowAnimation.automatic)
}

return textFieldCell
}
}

关于ios - 完成编辑单元格内的 TextView 后,将另一个单元格添加到 TableView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54101003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com