ios - swift 3 : Get an action button to trigger a TableView

标签 ios swift action-button

美好的一天,我想要一个在我的 TableView 外的按钮,它会触发显示 TableView (TableView 文本一开始是空白的,然后在我单击操作按钮后显示)。所有这些都发生在同一个 View Controller 中。这是我的 TableView 代码:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return postData2.count
}


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 
-> UITableViewCell {

                let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell2")

                let label1 = cell?.viewWithTag(1) as! UILabel
                label1.text = postData2[indexPath.row]

                return cell!
            }

如您所见,我在那里也有一个标签用于格式化。不知道会不会影响文字的触发。 这是我的空操作按钮的代码:

@IBAction func button2(_ sender: Any)
    {

    }

谢谢。

最佳答案

有许多不同的方法可以做到这一点。最简单的方法之一是在您开始时隐藏您的表格 View ,然后在单击按钮时显示表格 View 。像这样的东西:

@IBAction func button2(_ sender: Any) {
    tableView.hidden = false
}

但实际实现可能会有所不同,具体取决于您要实现的其他目标。例如,您可能希望表格 View 始终可见,但不希望在点击按钮之前显示任何数据。在这种情况下,您必须采取一些不同的措施。

您可以实现一个变量来指示是否要在 TableView 中显示数据。

var showData = false

然后实现numberOfRowsInSection,如果showData为真,返回实际行数,否则返回0。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return showData ? <actual row count> : 0
}

这样,您可以控制何时显示数据以及何时不显示数据。当然,您必须在按钮单击方法中将 showData 设置为 true 并重新加载数据。像这样:

@IBAction func button2(_ sender: Any) {
    showData = true
    tableView.reloadData()
}

关于ios - swift 3 : Get an action button to trigger a TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43024475/

相关文章:

r - Shiny :如果 radioButtions() 为空/未选中​​,actionButton() 能否返回错误?

ios - 从 Swift 类访问 Objective-c 基类的实例变量

ios - RestKit:将嵌套数组映射到对象

android - 免费向现有客户分发付费应用程序

ios - 显示部分标题 UICollectionReusableView

ios - 当 API 使用 MVVM 完成时重新加载 TableView

ios - 当按下 uicollectionviewcell 中的某些内容时如何通知 Controller

ios - 如何修复Mac o链接器(id错误)

ios - 在运行时隐藏通知操作按钮

javascript - 点击操作按钮的那一刻