Swift实现视图拉伸效果

时间:2023-02-09 14:06:16

头部视图拉伸效果

  • 1.创建ViewController,懒加载collectionView
    // MARK: - 懒加载collectionView
private lazy var collectionView : UICollectionView = {

let rect = CGRectMake(0, 0, ScreenRect.width, ScreenRect.height)
// 自定义flowLayout
let flowLayout = WYCollectionViewFlowLayout()
let collectionView = UICollectionView(frame: rect, collectionViewLayout: flowLayout
        // 设置数据源
        collectionView.dataSource = self
// 注册
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: CellID)
collectionView.registerClass(WYHeadView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: HeadID)

return collectionView
}()
  • 2.实现UICollectionView的数据源方法
// MARK: - 数据源方法
extension ViewController : UICollectionViewDataSource{

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return 15
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellID, forIndexPath: indexPath)

cell.backgroundColor = UIColor.grayColor()
return cell
}

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

let headView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: HeadID, forIndexPath: indexPath) as! WYHeadView
headView.imgName = "01.jpg"

return headView

}
}
  • 3.自定义flowLayout
 override func prepareLayout() {
super.prepareLayout()

headerReferenceSize = CGSizeMake(ScreenRect.width,300)
itemSize = CGSizeMake(ScreenRect.width,40)
}

override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

// 获取可见范围内的Elements
let attributes = super.layoutAttributesForElementsInRect(rect)

let offset = self.collectionView?.contentOffset
if offset?.y < 0 { // 用户向下拉

let deltay = fabs((offset?.y)!)

for attr in attributes!{

let kind = attr.representedElementKind
if kind == UICollectionElementKindSectionHeader{
// 获取headView的frame
var rect = attr.frame
// 改变headView的高度,y值
rect.size.height += deltay
rect.origin.y -= deltay

attr.frame = rect

}

}
}
return attributes
}
  • 4.自定义HeadView

var imgName : String?{

didSet{
imageView.image = UIImage(named: imgName!)
}
}
override init(frame: CGRect) {
super.init(frame: frame)

setUpUI()
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

func setUpUI(){

addSubview(imageView)
imageView.backgroundColor = UIColor.yellowColor()
}

override func layoutSubviews() {
super.layoutSubviews()

imageView.frame = self.bounds
}
private lazy var imageView : UIImageView = UIImageView()
}

效果图:

Swift实现视图拉伸效果