ios - 快速单击按钮时更改 tableView 文本标签

标签 ios swift xcode tableview

单击不同按钮时如何更改 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/

相关文章:

ios - 如何在 iOS 中下载 YouTube 视频

ios - 设置 UIActivityIndi​​catorView 背景

xcode - Ionic1 - Cordova-ios - 配置文件推送通知错误

iphone - 折叠代码的某些部分(变量声明和 if block )

php - 从 iPhone 应用程序 -> PHP -> MySQL 保护用户密码的最佳方法是什么?

iphone - Facebook IOS SDK 提要帖子可见性

ios - 快速日期格式化,从服务器返回的日期与发送到服务器的日期不同

ios - 按索引过滤数组

ios - 在 Swift 中将一个默认属性值传递给另一个

ios - 使用 Assets 时如何在 Xcode 5 中关闭图标光泽效果?