當(dāng)tableview下拉時(shí)拒名,頭部高度隨之改變。如圖所示芋酌。
1.gif
實(shí)現(xiàn)思路:
1增显、添加view到tableview上,設(shè)置tableView的contentInset脐帝,這樣同云,tableview上部分就空出來(lái)了,剛好顯示出view堵腹。
2炸站、在scrollViewDidScroll中,根據(jù)滑動(dòng)的距離疚顷,設(shè)置headerView的高度和y旱易。因?yàn)槲覀冃枰獙eaderview固定在頂部,所以y值也要調(diào)整腿堤。
有很多都是下拉圖片放大的效果咒唆,可以根據(jù)下拉的距離來(lái)改變scale transform。
需要注意的是:改變了contentInset之后释液,contentOffset會(huì)變化全释,其實(shí)也是改變了tableview的bounds。假設(shè)contentInset.top = 20误债,則contentOffset = -20, bounds.y = -20浸船。bounds的改變,會(huì)影響subview的布局寝蹈。 默認(rèn)bounds.origin = CGPointZero李命,(0, 0)就在左上角,如果我們改變了bounds.y = 20箫老,那么(0, 20)這個(gè)坐標(biāo)才會(huì)顯示在左上角封字,相當(dāng)于上移了20。
主要代碼如下:
創(chuàng)建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!)
}
監(jiān)聽(tīng)scroll
func scrollViewDidScroll(scrollView: UIScrollView) {
// 若設(shè)置了contentInset.top耍鬓,此時(shí)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)
}
}