UITableView头部下拉放大网上很多实现方式,使用过程会感觉很炫酷,实际实现起来成本确很低,两种实现方式供参考.
ContentInset实现
自定义UITableView,数据初始化:
<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: "简书", items: ["FlyElephant", "keso"]),
ExpandSection(title: "编程语言", items: ["Swift", "Objective-C", "JavaScript", "Python"]),
ExpandSection(title: "地区", items: ["北京", "河南", "江西"]),
]`</code></pre>
顶部头部设置:
<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>
实现UIScrollViewDelegate:
<pre><code>` func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY:CGFloat = scrollView.contentOffset.y
if offsetY < 0 {
headerImgView.y = offsetY
headerImgView.height = -offsetY
}
}`</code></pre>
实现效果下拉放大效果能实现,UITableView向上互动会有瑕疵,效果如下:
自定义UITableHeaderView
初始化数据不变,自定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中下拉过程需要对视图进行等比例放大及平移,停止下来的时候置为初始状态:
<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>
效果图如下: