[英]Swift: How to add a popup screen with label when a button is pressed in TableViewCell
[英]how to add label text to tableViewCell
我正在練習創建一個應用程序,其中有一個標簽,當用戶按下按鈕時,該標簽從 UITextField 獲取其文本。 現在,我添加了另一個按鈕和一個 tableview,我希望能夠使用與秒表圈數相同的機制將標簽的文本“保存”到表格單元格中。 所以,要清楚的是,我希望每次按下按鈕時都將標簽的文本傳輸到表格視圖單元格。
保存按鈕后,您需要將文本存儲在某處並重新加載表格。 (或者用動畫插入)
class ViewController: UIViewController {
@IBOutlet private var textField: UITextField!
@IBOutlet private var tableView: UITableView!
var texts: [String] = [] {
didSet { tableView.reloadData() }
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "SimpleCell")
tableView.dataSource = self
}
@IBAction func saveButtonTapped(_ sender: UIButton) {
guard let newText = textField.text else { return }
self.texts.append(newText)
}
}
在tableView
數據源方法中:
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return texts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SimpleCell", for: indexPath)!
cell.textLabel?.text = texts[indexPath.row]
return cell
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.