当 tableview 下拉时,头部高度随之改变。如图所示。
1.gif
实现思路:
1、添加 view 到 tableview 上,设置 tableView 的 contentInset,这样,tableview 上部分就空出来了,刚好显示出 view。
2、在 scrollViewDidScroll 中,根据滑动的距离,设置 headerView 的高度和 y。因为我们需要将 headerview 固定在顶部,所以 y 值也要调整。
有很多都是下拉图片放大的效果,可以根据下拉的距离来改变 scale transform。
需要注意的是:改变了 contentInset 之后,contentOffset 会变化,其实也是改变了 tableview 的 bounds。假设 contentInset.top = 20,则 contentOffset = -20, bounds.y = -20。bounds 的改变,会影响 subview 的布局。 默认 bounds.origin = CGPointZero,(0, 0)就在左上角,如果我们改变了 bounds.y = 20,那么 (0, 20) 这个坐标才会显示在左上角,相当于上移了 20。
主要代码如下:
创建 header
var headerView: UIView?
let headerViewHeight: CGFloat = 44
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.contentInset = UIEdgeInsetsMake(headerViewHeight, 0, 0, 0)
headerView = UIView()
// 注意y值
headerView!.frame = CGRectMake(0, -headerViewHeight, view.bounds.size.width, headerViewHeight)
headerView!.backgroundColor = UIColor.redColor()
tableView.addSubview(headerView!)
}
监听 scroll
func scrollViewDidScroll(scrollView: UIScrollView) {
// 若设置了contentInset.top,此时contentOffset.y = -contentInset.top - realOffset
let contentOffsetY = scrollView.contentOffset.y
// real scroll offset
let totalOffsetY = scrollView.contentInset.top + contentOffsetY
print("contentOffsetY:\(contentOffsetY), totalOffsetY:\(totalOffsetY)")
if let headerView = headerView {
var size = headerView.frame.size
size.height = headerViewHeight - totalOffsetY
headerView.frame = CGRectMake(0, contentOffsetY, size.width, size.height)
}
}