当没有足够的行来填充 tableView 时,所有现有的解决方案都不适用于 iOS 8,因为 iOS 会在这种情况下自动调整插图。 (但是,当有足够的行时,现有答案很好)
在这个问题上浪费了大约 6 个小时后,我终于得到了这个解决方案。
简而言之,如果单元格不足,则需要在tableView中插入空单元格,因此tableView的内容大小足够大,iOS不会为您调整inset。
这是我在 Swift 中的做法:
1.) 将变量minimumCellNum 声明为类属性
var minimumCellNum: Int?
2.) 计算minimumCellNum 并在viewWillAppear 中设置tableView.contentOffset
let screenHeight = Int(UIScreen.mainScreen().bounds.height)
// 101 = Height of Status Bar(20) + Height of Navigation Bar(44) + Height of Tab Bar(49)
// you may need to subtract the height of other custom views from the screenHeight. For example, the height of your section headers.
self.minimumCellNum = (screenHeight - 103 - heightOfOtherCustomView) / heightOfYourCell
self.tableView.contentOffset = CGPointMake(0, 44)
3.) 在tableView(tableView: UITableView, numberOfRowsInSection section: Int))
let numOfYourRows = YOUR LOGIC
if numOfYourRows > minimumCellNum {
return numOfYourRows
} else {
return minimumCellNum!
}
4.) 在情节提要和tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) 中注册一个selection 属性为None 的空单元格
if indexPath.row < numOfYourRows {
return YOUR CUSTOM CELL
} else {
let cell = tableView.dequeueReusableCellWithIdentifier("EmptyCell", forIndexPath: indexPath) as! UITableViewCell
return cell
}
5.) 在tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
if tableView == self.tableView {
if numOfYourRows < (indexPath.row + 1) {
return
}
YOUR LOGIC OF SELECTING A CELL
}
这不是一个完美的解决方案,但它是在 iOS 8 上真正适合我的唯一解决方法。我想知道是否有更简洁的解决方案。