我希望 tableview 插入一个新行,其中的文本对应于我按下的特定按钮,但我不确定如何在我的代码/UI 中指定它。
基本上,我希望在按下按钮 #1 时显示文本“按钮 #1 已按下”,在按下按钮 #2 时显示“按钮 #2 已按下”,等等。我该如何配置它?
TableViewController.swift
import UIKit
class TableViewController: UITableViewController {
var myArray = ["button #1 pressed", "button #2 pressed", "button #3 pressed"]
override func viewDidLoad() {
super.viewDidLoad(
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = self.FruitVegArray[indexPath.row]
return cell
}
}
SubViewController.swift
import UIKit
class SubViewController: UIViewController {
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let tableVC = segue.destination as! TableViewController
}
@IBAction func button1action(_ sender: Any) {
}
@IBAction func button2action(_ sender: Any) {
}
}
最佳答案
将 myArray 初始化为空白
var myArray = [String]()
并从 myArray 返回行数。
override func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return myArray.count
}
现在,当按下 button1 时,只需在数组中添加“button #1 pressed”文本并刷新表格 View 。您需要从“SubViewController”类访问 myArray,然后添加文本。
myArray.append("button #1 pressed")
tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: myArray.count-1, section: 0)], with: .automatic)
tableView.endUpdates()
与按钮 2 或其他按钮相同。
关于swift - 如何让 tableview 在 Swift 4.0 中每次按下按钮时显示数组中的一个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47428807/