import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
let headerViewHeight: CGFloat = 500
private lazy var headerView: UIView = {
let view = UIView(frame: CGRect(x: 0, y: -headerViewHeight, width: UIScreen.main.bounds.width, height: headerViewHeight))
view.clipsToBounds = true
return view
}()
private lazy var imageView: UIImageView = {
let view = UIImageView(image: UIImage(named: "image"))
view.frame = headerView.bounds
return view
}()
private lazy var collectionView: UICollectionView = {
let view = UICollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), collectionViewLayout: UICollectionViewFlowLayout())
view.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "UICollectionViewCell")
view.delegate = self
view.dataSource = self
view.contentInset = UIEdgeInsets(top: headerViewHeight, left: 0, bottom: 0, right: 0)
view.backgroundColor = .white
view.contentInsetAdjustmentBehavior = .never
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
collectionView.addSubview(headerView)
headerView.addSubview(imageView)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.y
// 重新赋值,防止用力拖拽时的回弹
imageView.frame.origin.y = 0
if (offset >= -headerViewHeight && offset <= headerViewHeight) {
imageView.frame.origin.y = (offset + headerViewHeight) * 0.5
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 600
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UICollectionViewCell", for: indexPath)
cell.backgroundColor = UIColor(red: CGFloat(arc4random() % 256) / 255.0, green: CGFloat(arc4random() % 256) / 255.0, blue: CGFloat(arc4random() % 256) / 255.0, alpha: 1.0)
return cell
}
}
iOS UICollectionView、UITableView 滚动与头部图片视觉差效果
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 淘宝App的商品详情页,在向上滑动的时候,顶部图片会以一个比较慢的速度向上滑动,并慢慢被详情页覆盖,我也不知道这种...
- 一.位置确定 img = [[UIImageView alloc]initWithFrame:CGRectMake...
- 最近感觉UITableview头部带有图片,并且下拉时图片放大这种效果非常炫酷,所以动手实现了一下,效果如下图: ...
- 工程中要实现UITableView 头部图片下拉放大效果,实现了以后想把过程记录下来。 基本思路:我是将头部上面的...