noblerare noblerare -4 years ago 74
iOS Question

Swift - Customize view to show over an empty table cells

I am using Swift 3, Xcode 8.2.

I've been able to create a label to cover the empty table view cells when there are none to display.

My code is below and it is located in the subclass of

UITableViewController
.

override func numberOfSections(in tableView: UITableView) -> Int {

// if there are scans to display...
if items.count > 0 {
tableView.backgroundView = nil
tableView.separatorStyle = .singleLine
return 1
}
else { // otherwise, return 0, remove cell lines, and display a Label
let rect = CGRect(x: 0,
y: 0,
width: tableView.bounds.size.width,
height: tableView.bounds.size.height)
let noScanLabel: UILabel = UILabel(frame: rect)

noScanLabel.text = "No Scans"
noScanLabel.textColor = UIColor.gray
noScanLabel.font = UIFont.boldSystemFont(ofSize: 24)

noScanLabel.textAlignment = NSTextAlignment.center



tableView.backgroundView = noScanLabel
tableView.separatorStyle = .none



return 0
}
}


Here is the result.

enter image description here

Looks fine. But how, do I make it such that I include another line of text with a downward arrow pointing at the raised center button. Something like "Click here to start a scan"?

I've tried adding new line characters to the
noScanLabel.text
field but that didn't work out. Any pointers in the right direction would be helpful.

Answer Source

The simple solution is to set numberOfLines to 0 on noScanLabel. This way, the new lines will show.

let noScanLabel: UILabel = UILabel(frame: rect)

noScanLabel.text = "No Scans"
noScanLabel.textColor = UIColor.gray
noScanLabel.font = UIFont.boldSystemFont(ofSize: 24)
noScanLabel.numberOfLines = 0

noScanLabel.textAlignment = NSTextAlignment.center

Note than in such cases, I would recommend, for better maintainability, to actually remove the TableView from the UIViewController (hence not inherit from UITableViewController) and replace it with an empty view when you detect no scans are available. This will make each state more independent of each other and make maintenance easier.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download