iOSMAn iOSMAn - 1 year ago 165
Swift Question

UITableView rows sliding under UITableViewHeaderSection

I have a UITableView populating this sample Dictionary.

var WholeDict = [
"Animals" : ["Cat","Dog"],
"Fruits" : ["Apple","Orange"]

The content is too small. So I am choosing the grouped UITableView style, so that I can avoid the unwanted cells that is showing below the content in UITableView. But the problem is, when I choose grouped style, the cells under each sections are not going under header when scrolling. The scrolling moves the header first.
Grouped style: cells scrolling along with header &
Plain style: cells sliding under header. This is what I am doing in code

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let allkeys = Array(WholeDict.keys)
return allkeys[section]

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let headerView = view as? UITableViewHeaderFooterView {
headerView.textLabel?.textAlignment = .Center

So how can I avoid the extra spaces below the tableview and at the same time use the sliding of rows under headers?

I am using walters answer. It is working for me. But then I had another issue. When I am scrolling beyond the last row, then the screen will show only the footer that I had added. So I added another workaround.

func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let visiblerows = MyTable.indexPathsForVisibleRows
if visiblerows?.count == 0 {
let ScrollToIndexPath = NSIndexPath(forRow: 0, inSection: WholeDict.count - 1)
MyTable.scrollToRowAtIndexPath(ScrollToIndexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)

Answer Source

The UITableView will always add blank "cells" to fill out the space. In order to make them go away you should create a footerView that fills the space between the bottom of the last populated row and the bottom of the tableView. Here is a quick example but you may need to move it around depending on how you add cells. The tableView's contentSize property will have a height that is equal to the populated part of the tableView.

 let contentSize = self.tableView.contentSize
 let footer = UIView(frame: CGRect(x: self.tableView.frame.origin.x, 
                                   y: self.tableView.frame.origin.y + contentSize.height, 
                               width: self.tableView.frame.size.width,
                              height: self.tableView.frame.height - self.tableView.contentSize.height))

  self.tableView.tableFooterView = footer
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download