繁体   English   中英

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

[英]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

1.解决方案

添加一个类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错误)

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()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM