问题
I have a tableview, which I use as a part of the screen.
@IBOutlet var tableView: UITableView!
Sometimes I have data, and sometimes I don't. I want to display the table only when data is present and hide it when there is no data.
I tried adding a constraint of height with lesser or equal to options. But if I do that, tableview is hidden even when I have data
what should I do?
I googled around and didn't find a solution, so asking here.
Disclaimer: I am new to iOS/Swift development. Sorry if this is already answered
回答1:
You can show hide tableView like below.
You can check the count using the array with which you might be populating the data Or with the tableView property numberOfRowsInSection.
when there is no data
tableView.ishidden = true
when there is data
tableView.ishidden = false
Or you can use the delegate method as below.
override func viewWillAppear(_ animated: Bool) {
if array.isEmpty {
self.tableView.isHidden = true
}
else {
self.tableView.isHidden = false
}
}
More better way would be using didSet.
var dataArray: [String] = [] {
didSet {
if dataArray.count > 0 {
//Update Table Data
} else {
//Hide Table and show so info of no data
}
}
}
回答2:
You can also try this, so that you can make use of the empty table space.
Set outlet to your table height constraint and add the below line
tableHeightConstraint.constant = array.count != 0 ? 250 : 0
回答3:
Set tableView.isHiden = true if no data to present.
来源:https://stackoverflow.com/questions/42430856/swift3-hide-uitableview-if-empty