单击不同按钮时如何更改 tableView textLabel。我有两个操作按钮brandButton和profileButton,我想要发生的是当我单击brandButton时brandInformation将显示在tableView文本标签上,当我单击profileButton时profileInformation将显示。
import UIKit
class StreamDetailController: UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var tableViewController: UITableView!
var brandInformation = ["Hat:","Top:","Pants:","Shoes"]
var profileInformation = ["tim", "master"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return brandInformation.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableViewController.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = brandInformation[indexPath.row]
return cell
@IBAction func brandButton(_ sender: Any) {
}
@IBAction func profileButton(_ sender: Any) {
}
最佳答案
注意:
在这一行中:
@IBOutlet weak var tableViewController: UITableView!
该变量是错误的并且可能会造成困惑。 tableViewController
应重命名为 tableView
1。解决方案
添加一个类变量来保存您想要查看的 View 并使用按钮更改它。然后在表格上调用reloadData
来刷新内容:
cell.textLabel?.text = brandInformation[indexPath.row]
至
var isShowBrand = true
// [...]
if isShowBrand {
cell.textLabel?.text = brandInformation[indexPath.row]
} else {
cell.textLabel?.text = profileInformation[indexPath.row]
}
以及行计数(您还可以使用三元运算符:
return isShowBrand ? brandInformation.count : profileInformation.count
(如果您想按单元格保存它,那么您需要像保存单元格数据一样保存此信息 var showBrand = [true, false]
- 但请检查所有 3 个数组是否都具有相同的项目数以避免索引越界
错误)
2。解决方案
只需创建一个额外的数组tableData
,然后在按钮中设置您需要查看的数组。所有数据填充均通过 tableData
数组完成(您需要将所有 brandInformation
更改为 tableData
)
var tableData = [String]()
// [...]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableViewController.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = tableData[indexPath.row]
return cell
}
// [...]
@IBAction func brandButton(_ sender: Any){
tableData = brandInformation
tableViewController.reloadData()
}
@IBAction func profileButton(_ sender: Any){
tableData = profileInformation
tableViewController.reloadData()
}
关于ios - 快速单击按钮时更改 tableView 文本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41863222/