![](/img/trans.png)
[英]How to change textLabel outside CollectionView when cell is clicked in Swift 4?
[英]Change tableView textlabel when button is clicked swift
单击不同的按钮时如何更改tableView textLabel。 我有两个操作按钮brandButton和profileButton,我要发生的事情是当我单击brandButton时,brandInformation将显示在tableView textLabel中,而当我单击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
添加一个类var来保存您想要查看的视图并使用按钮对其进行调整。 然后在表上调用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个数组的项数是否相同,以避免index out of bounds
错误)
只需再创建一个数组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()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.