

Here is my scenario. First of all, my table view is static. And in section "Account", there should alway be only one cell displayed. LoggedInCell is displayed when user is logged in, and unLoggedInCell when user is not logged in.
One solution is to set their height zero, but you may encounter NSContraints error which is complex to be fixed.
My solution is below:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let count = super.tableView(tableView, numberOfRowsInSection: section)
if section == 0 {
return count - 1
}
return count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if userForApp == nil {
return super.tableView(tableView, cellForRowAt: IndexPath(row: 0, section: 0))
} else {
return super.tableView(tableView, cellForRowAt: IndexPath(row: 1, section: 0))
}
} else {
return super.tableView(tableView, cellForRowAt: indexPath)
}
}
quite simple! yes?
Btw, You may have the cells height problem like me, I mean the two cells (UnLoggedInCell and LoggedInCell) have different height, we should tell the table view object that the value of cells height by doing this:
var originHeightOfUnLoggedInCell: CGFloat = 0.0
var originHeightOfLoggedInCell: CGFloat = 0.0
func recordInitialHeightOfCells() { // called in viewDidLoad()
self.originHeightOfUnLoggedInCell = self.unLoggedInCell.frame.height
self.originHeightOfLoggedInCell = self.loggedInCell.frame.height
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
if userForApp == nil {
return originHeightOfUnLoggedInCell
} else {
return originHeightOfLoggedInCell
}
} else {
return super.tableView(tableView, heightForRowAt: indexPath)
}
}