UITableViewOrUICollectionView下拉顶部图片拉伸效果

先说说我起始的做法把
  • 1、 设置UICollectionView的基本相关属性
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _goodsCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, XKScreenWidth, XKScreenHeight) collectionViewLayout:flowLayout];
    _goodsCollectionView.backgroundColor = [UIColor whiteColor];
    _goodsCollectionView.delegate = self;
    _goodsCollectionView.dataSource = self;
    //偏移量(预留出顶部图片的位置)
    _goodsCollectionView.contentInset = UIEdgeInsetsMake(TopImgHeight, 0, 0, 0 );

  • 2、创建topImgView并添加到CollectionView

//TopImgHeight-->宏定义的图片高度
_topImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -TopImgHeight, XKScreenWidth, TopImgHeight)];   
//重点(不设置那将只会被纵向拉伸) 
_topImgView.contentMode = UIViewContentModeScaleAspectFill;
[self.goodsCollectionView insertSubview:self.topImgView atIndex:0];
  • 3、在ScrollerViewDelegate修改图片尺寸
CGFloat y = scrollView.contentOffset.y;
    if (y < -TopImgHeight) {
// 为了拉伸顶部图效果     操作topImgView
     CGRect imgframe = self.topImgView.frame;
    imgframe.origin.y = y;
    imgframe.size.height = -y;
    self.topImgView.frame = imgframe
    }
  • 4、如果self.topImgView内有子控件,需要设置相关属性
//设置autoresizesSubviews让子类自动布局 
self.topImgView.autoresizesSubviews = YES;       
//自动布局,自适应顶部
topImgVSubV.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
本人刚开始就是用上面做法做的,但后来发现当TopImgHeight设置少点时,将遮挡下面的cell ,效果很不好,进行如下修改效果就完善了
  • 1、不用设置_topImgView.contentMode用默认的就可以了
  • 2、在ScrollerViewDelegate中同时修改X、Y、W、H
    CGFloat y = scrollView.contentOffset.y;
if (y < -TopImgHeight) {
//        为了拉伸顶部图效果     操作topImgView(缺点:图片尺寸不同
//        时,有时会遮挡collectionV)
//        CGRect imgframe = self.topImgView.frame;
//        imgframe.origin.y = y;
//        imgframe.size.height = -y;
//        self.topImgView.frame = imgframe;
//--------------------------修改后--------------------------------
        /** 让其XYWH都‘拉伸’ */
 /** Ky --> 正值的下拉多少距离的值,Kx--> 根据Ky成比例的让x变 */
        CGFloat Ky = -scrollView.contentOffset.y-TopImgHeight;
        CGFloat Kx = (Ky/TopImgHeight)*XKScreenWidth/2;
        self.topImgView.frame = CGRectMake(0-Kx, 0-Ky-TopImgHeight,
        XKScreenWidth+2*Kx, TopImgHeight+Ky);
    }
//---------------------------------------------------------------

OK! 这样基本就完成效果了,如果有需求让导航栏上推渐变的话,也只需要在scrollV的滑动代理内操作即可(以下代码本人是使用的自定义nav)

CGFloat y = scrollView.contentOffset.y;
CGFloat alphaOffset = (100+y) / (NavViewHeight) ;
//    NSLog(@"alphaOffset  %lf",alphaOffset);
if (alphaOffset >= 1.0) {
    [UIView animateWithDuration:0.04 animations:^{
        self.navbgImgView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:1];
    }];
}
else
{
    self.navbgImgView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
}
self.navbgImgView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:alphaOffset];

你可能感兴趣的:(UITableViewOrUICollectionView下拉顶部图片拉伸效果)