0

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

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

内容太少了。所以我选择了分组的 UITableView 样式,这样我就可以避免在 UITableView 的内容下方显示不需要的单元格。但问题是,当我选择分组样式时,每个部分下的单元格在滚动时不会在标题下。滚动首先移动标题。 分组样式:单元格与标题一起滚动普通样式:单元格在标题下滑动。这就是我在代码中所做的

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

那么如何避免表格视图下方的额外空格,同时使用标题下的行滑动呢?

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

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

2 回答 2

1

UITableView始终添加空白“单元格”来填充空间。为了使它们消失,您应该创建一个填充最后填充行底部和 tableView 底部之间的空间的 footerView。这是一个简单的示例,但您可能需要根据添加单元格的方式来移动它。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
于 2016-05-07T02:13:00.397 回答
0

如果您希望固定部分标题,则可以使用此属性。

self.tableView.style = UITableViewStyleGrouped

它使您的部分标题粘在行上并与它们一起滚动。

于 2016-05-05T08:57:12.790 回答