Reputation: 59
Good day, I would like a button outside my table view that would trigger showing the table view (TableView text blank at first, then for it to show after I click the action button). All of this happens in the same view controller. This is my code for the 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!
}
As you can see, I have a label there too for formatting purposes. I don't know if it will affect the triggering of the text. Here's the code for my empty action button:
@IBAction func button2(_ sender: Any)
{
}
Thanks.
Upvotes: 0
Views: 1975
Reputation: 3556
There are many different ways you can do this. One of the easiest would be to have your table view hidden when you start and then show the table view on the click of the button. Something like:
@IBAction func button2(_ sender: Any) {
tableView.hidden = false
}
But the actual implementation might have to differ depending on what else you are trying to achieve. For example, you might want the table view to be always visible but don't want any data displayed there till you tap the button. In that case, you'd have to do something a little bit different.
You can implement a variable to indicate whether you want to display data in the table view or not.
var showData = false
Then implement the numberOfRowsInSection
to return the actual number of rows if showData
is true, otherwise, return 0.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return showData ? <actual row count> : 0
}
This way, you can control when data is shown and when it is not. Of course, you'd have to set showData
to true in your button click method and reload the data. Like this:
@IBAction func button2(_ sender: Any) {
showData = true
tableView.reloadData()
}
Upvotes: 2