@ octy的答案將適用於iOS 9.但是,對於iOS 10,似乎tableView的contentSize包含tableViewFooter高度。在iOS 10中,我不得不做以下事情:
var rowDataBounds: CGRect {
get {
if numberOfSections <= 0 {
return CGRect(x: 0, y: 0, width: frame.width, height: 0)
}
else {
let minRect = rect(forSection: 0)
let maxRect = rect(forSection: numberOfSections-1)
return maxRect.union(minRect)
}
}
}
fileprivate func resizeFooterView(){
if let footerView = tableFooterView {
var newHeight: CGFloat = 0
let tvFrame = self.frame;
if #available(iOS 10, *) {
newHeight = tvFrame.size.height - rowDataBounds.height - self.contentInset.bottom - self.contentInset.top
}
else {
newHeight = tvFrame.size.height - self.contentSize.height
}
if newHeight < 0 {
newHeight = 0
}
let frame = footerView.frame
if newHeight != frame.height {
footerView.frame = CGRect(x:frame.origin.x, y:frame.origin.y, width:frame.size.width, height: newHeight)
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
resizeFooterView()
}