ios - UITableView 行在 UITableViewHeaderSection 下滑动

标签 ios iphone swift uitableview uitableviewsectionheader

我有一个 UITableView 填充这个示例字典。

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

内容太少。所以我选择分组的 UITableView 样式,这样我就可以避免在 UITableView 的内容下方显示不需要的单元格。但问题是,当我选择分组样式时,滚动时每个部分下的单元格不会在标题下。滚动首先移动标题。 Grouped style: cells scrolling along with header & Plain style: cells sliding under header .这就是我在代码中所做的

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
    }
}

那么如何避免tableview下方的多余空格,同时在header下使用行的滑动呢?

编辑 我正在使用沃尔特斯的回答。它对我有用。但后来我遇到了另一个问题。当我滚动到最后一行之后时,屏幕将只显示我添加的页脚。所以我添加了另一个解决方法。

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)
    }
}

最佳答案

UITableView 将始终添加空白“单元格”来填充空间。为了让它们消失,你应该创建一个 footerView 来填充最后填充行的底部和 tableView 底部之间的空间。这是一个简单的示例,但您可能需要根据添加单元格的方式来移动它。 tableView 的 contentSize 属性的高度将等于 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

关于ios - UITableView 行在 UITableViewHeaderSection 下滑动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37043200/

相关文章:

ios - 需要从每个名称的倍数的数组中获取名称列表(每个名称只有 1 个实例)

ios - ScrollView 中的 TableView

ios - Swift:字符后的字符串firstIndex

html - 如何在 swift 中从 html 字符串转换 NSAttributedString?

ios - 使用 KVO 跟踪 NSArray 计数的变化

ios - Swift Google Map Marker Tap 事件对我不起作用

ios - 使用 animationImages 检测在 UIImageView 中单击了哪个图像

ios - 如何同时滑入/滑出状态栏和导航栏?

iphone - iOS 上 RAM 中连续数据的安全大小?

ios - 仅当用户快速锁定时,如何运行 func applicationDidEnterBackground 代码?