【问题标题】:Change label text of tableView on button click Swift在按钮单击Swift时更改tableView的标签文本
【发布时间】:2021-08-06 12:18:54
【问题描述】:

我做了一个简单的应用来练习 tableView 和 Singletons。我是 swift 新手,所以我希望能得到一些快速帮助。我想做的事情很简单,但我现在什么都想不起来。

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

    var tableView = UITableView()
    let names = Singleton.shared.nameArray
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tableView)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.delegate = self
        tableView.dataSource = self
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        tableView.frame = .init(x: 0, y: 0, width: 414, height: 260)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return names.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let name = names[indexPath.row]
        cell.textLabel?.text = "cell \(indexPath.row + 1)"
        return cell
    }
    @IBAction func didPressButton(_ sender: Any) {
           
       }
}

基本上我希望 tableView 标签更改为我在单击按钮后创建的 name 常量。 对不起,如果我没有在问题中说明一切,我希望你能理解并能够帮助我。解释代码有点困难,因为我是 swift 新手,而且英语不是我的母语。

进行了编辑以澄清一些事情。

【问题讨论】:

  • 按下按钮后,您正在更改名称数组的元素?或者你是怎么改名字的?
  • 不,我希望名称数组的元素在按下按钮后显示在表格视图中,而不是从一开始就显示在表格视图中

标签: ios swift tableview


【解决方案1】:

添加到 ViewController:

private var areNamesVisible = false

@IBAction func didPressButton(_ sender: Any) {
    areNamesVisible.toggle()
    tableView.reloadData()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let name = names[indexPath.row]
    cell.textLabel?.text = areNamesVisible ? name : "cell \(indexPath.row + 1)"
    return cell
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    相关资源
    最近更新 更多