美文网首页iOS学习记录
下拉放大的二种实现思路

下拉放大的二种实现思路

作者: 其实朕是一只程序猿 | 来源:发表于2015-12-25 08:04 被阅读984次

下拉放大的效果在很多电商类网站上都有应用,一般的情况是在tableView的最顶端放置1个UIView 或者UIScrollView控件,在tableView向下拖拽的时候,图片会从中心点向下产生放大的效果.下面就说一下两种效果略有不同 下拉放大效果的实现思路.备查.
两种下拉放大的实现思路:
第一种
首先在tableView的声明1个属性就是顶部的那个需要放大的imageView

#import "GZDTableViewController.h"
@interface GZDTableViewController ()
//顶部需要放大的View
@property (weak,nonatomic) UIImageView *topView;
@end
@implementation GZDTableViewController

在ViewDidLoad方法中加载这个view

- (void)viewDidLoad {
    [super viewDidLoad];
 //加载图片
    UIImage *foodImage = [UIImage imageNamed:@"food"];
  //通过图片创建imageView
    UIImageView *topView = [[UIImageView alloc] initWithImage:foodImage];
  //设置图片的填充模式
  //等比例缩放,图片不会变形.填充整个父控件
    topView.contentMode = UIViewContentModeScaleAspectFill;
//设置顶部View的frame 
    topView.frame = CGRectMake(0, -foodImage.size.height, foodImage.size.width, foodImage.size.height);
    //为了不挡住tableView的cell内容所以将顶部的View插入到最下面的一层.
        [self.tableView insertSubview:topView atIndex:0];
//给属性赋值
    self.topView = topView;
    //设置tableView 的内边距 这样顶部的view 就能够完全的展示出来,不会挡住cell.
    self.tableView.contentInset = UIEdgeInsetsMake(foodImage.size.height , 0, 0, 0);
}

tableView 继承自scrollView ,实现scrollView的代理方法监听手指的拖拽

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //由于scrollView 向下拖拽的contentOffset.y的值是负数.并且设置了contentInsets,这里这样设置可以将offset的初始值设置为0,下拉时为正数,方便判断.
        CGFloat offset = -(scrollView.contentOffset.y + self.topView.image.size.height);
   //image的宽高比
        CGFloat scale = self.topView.image.size.width / self.topView.image.size.height;
    //如果是向上拖动 返回.
        if (offset < 0) return;
//取出topView的frame
        CGRect frame = self.topView.frame;
//x值向左边移动-offset的距离
        frame.origin.x = -offset;
//由于在viewDidLoad方法中设置了topView 的图片填充模式,所以宽度拉伸之后,高度也会相应的拉伸.
    frame.size.width =(self.topView.image.size.height +2*offset) *scale;
    //重新赋值
        self.topView.frame = frame;

最后实现效果

basic.gif

另外一种效果是顶部的图片显示一半,在下拉的时候缓慢的将图片顶部没有显示出来的部分 显示出来,并且放大,代码更加简单
同样的项目
在ViewDidLoad方法中将tableView的内边距设置只有图片大小的一半

    #warning 这里的frame值 修改到只显示一半
 self.tableView.contentInset = UIEdgeInsetsMake(foodImage.size.height *0.5 , 0, 0, 0);

在scrollView的代理方法中

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
#warning 由于contentInset设置的是图片高度的一半,所以此处也设置为一半的高度
        CGFloat offset = -(scrollView.contentOffset.y +   self.topView.image.size.height *0.5);
        if (offset < 0) return;
//改变topView的frame
        CGRect frame = self.topView.frame;
//因为设置了topView的填充模式,所以只修改topView的高度就可以实现效果,宽度会等比例自适应,并且保证图片的中心始终在父控件的中心显示.
frame.size.height = self.topView.image.size.height + offset;
        self.topView.frame = frame;

最终效果

1.gif

这种方式更加简单,但是一般顶端图片的大小都仅仅占据顶部的一小块区域,使用这种方式加载的图片只要用户手指拖拽的够久 就能够看到最后面的背景.

相关文章

网友评论

    本文标题:下拉放大的二种实现思路

    本文链接:https://www.haomeiwen.com/subject/mbivhttx.html