UITableView頭部下拉放大網(wǎng)上很多實(shí)現(xiàn)方式问芬,使用過(guò)程會(huì)感覺(jué)很炫酷册倒,實(shí)際實(shí)現(xiàn)起來(lái)成本確很低蔫耽,兩種實(shí)現(xiàn)方式供參考.
ContentInset實(shí)現(xiàn)
自定義UITableView见秤,數(shù)據(jù)初始化:
<pre><code>` tableView = UITableView(frame: CGRect.init(x: 0, y: 64, width:self.view.bounds.width, height: self.view.bounds.height - 64), style: .plain)
tableView?.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "UITableViewCell")
tableView?.delegate = self
tableView?.dataSource = self
setUpTableHeader1()
self.view.addSubview(tableView!)
sections = [
ExpandSection(title: "簡(jiǎn)書(shū)", items: ["FlyElephant", "keso"]),
ExpandSection(title: "編程語(yǔ)言", items: ["Swift", "Objective-C", "JavaScript", "Python"]),
ExpandSection(title: "地區(qū)", items: ["北京", "河南", "江西"]),
]`</code></pre>
頂部頭部設(shè)置:
<pre><code>let frame:CGRect = CGRect(x: 0, y: -200, width: self.view.bounds.width, height: 200) headerImgView = UIImageView.init(image: UIImage.init(named: "Header.jpeg")) headerImgView.frame = frame headerImgView.contentMode = .scaleAspectFill tableView?.contentInset = UIEdgeInsetsMake(200, 0, 0, 0) tableView?.addSubview(headerImgView)
</code></pre>
實(shí)現(xiàn)UIScrollViewDelegate:
<pre><code>` func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY:CGFloat = scrollView.contentOffset.y
if offsetY < 0 {
headerImgView.y = offsetY
headerImgView.height = -offsetY
}
}`</code></pre>
實(shí)現(xiàn)效果下拉放大效果能實(shí)現(xiàn)控乾,UITableView向上互動(dòng)會(huì)有瑕疵幔欧,效果如下:
自定義UITableHeaderView
初始化數(shù)據(jù)不變,自定UITableHeaderView丽声,添加子視圖UIImageView
<pre><code>` func setUpTableHeader() {
let frame:CGRect = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 200)
tableHeaderView = UIView.init(frame: frame)
headerImgView = UIImageView.init(image: UIImage.init(named: "Header.jpeg"))
headerImgView.frame = frame
headerImgView.contentMode = .scaleAspectFill
tableHeaderView.addSubview(headerImgView)
tableView?.tableHeaderView = tableHeaderView
}`</code></pre>
UIScrollViewDelegate中下拉過(guò)程需要對(duì)視圖進(jìn)行等比例放大及平移礁蔗,停止下來(lái)的時(shí)候置為初始狀態(tài):
<pre><code>` func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY:CGFloat = scrollView.contentOffset.y
if offsetY < 0 {
let originalHeight:CGFloat = tableHeaderView.height
let scale:CGFloat = (originalHeight - offsetY) / originalHeight
let transformScale3D:CATransform3D = CATransform3DMakeScale(scale, scale, 1.0)
let translation3D:CATransform3D = CATransform3DMakeTranslation(0, offsetY/2, 0)
headerImgView.layer.transform = CATransform3DConcat(transformScale3D, translation3D)
} else {
headerImgView.layer.transform = CATransform3DIdentity
}
}
`</code></pre>
效果圖如下: