As shown in the image below, when you want to switch the display / non-display of the top margin depending on the condition in ʻUITableView where
styleis
grouped`, you made a trial and error, so make a note of the method.
Margin display | Hide margins |
---|---|
This time, I wanted to eliminate the margin when displaying the header like the image, and to have the margin when the header is not displayed. .. ..
The pattern that was useless for the time being. .. .. As shown below, when ʻisHeaderShown is
true`, I set the header in section 0 and set the height.
extension TableViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard section == 0 else {
return UITableView.automaticDimension
}
return isHeaderShown ? 50 : UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard section == 0 else {
return nil
}
return isHeaderShown ? HeaderView() : nil
}
}
result
Only the first display is good, but the second and subsequent times are strange. .. .. : frowning2:
Above method + I tried to play with tableHeaderView
when updating the table as shown below.
tableView.tableHeaderView = isHeaderShown ? UIView() : nil
tableView.reloadData()
result
Got it: tada:
It seems that the above method can be used, but if you set the header only at the top in the first place, I thought that it is not necessary to set View in sectionHeader, and finally I did as follows.
extension TableViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard section == 0 else {
return UITableView.automaticDimension
}
return isHeaderShown ? CGFloat.leastNormalMagnitude : UITableView.automaticDimension
}
}
//Processing at the time of update
tableView.tableHeaderView = isHeaderShown ? HeaderView(frame: .init(origin: .zero, size: .init(width: 0, height: 50))) : nil
tableView.reloadData()
The result was the same as pattern 1, so maybe it's okay: clap:
I think it's rare to want to have such a layout, but I hope it helps someone. If you know any other good way, please let me know: pray:
I've heard that it's better to use ʻUICollectionView rather than ʻUITableView
in the future, and it may not be good to clutter the table too much anymore. .. .. : thinking:
Recommended Posts