swift - 如何让 tableview 在 Swift 4.0 中每次按下按钮时显示数组中的一个项目?

标签 swift

我希望 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/

相关文章:

ios - 如何使用 Xcode 基于 UItableViewCell 中的手势操作触发 UIViewController segue

ios - 从本地库传递图像的 url

java - 如何使用 Appium 在 iOS 中滑动

ios - Swift - 从 AppDelegate 添加 subview 到 View Controller

java - 什么是 Swift 字典的 Android Java 等价物?

swift - 检查非可选值是否为零

ios - 使用不同数据从 ViewController 到自身的动画/Segue - Swift

ios - 使用activityController共享标签

swift - 实例方法 'match(match:player:didChangeState:)'几乎匹配协议(protocol) 'match(_:player:didChange:)'的可选要求 'GKMatchDelegate'

swift - 为什么@optional 修饰的属性会变成不可变的?