iOS点击图片查看大图,自由缩放功能的实现

2020-04-22  本文已影响0人  忆一曲肝肠断

在我们开发项目中,经常会遇到点击图片查看图片大图,而且可以自由缩放的功能,今天就讲一讲它的实现方法

- (void)viewDidLoad {

    [super viewDidLoad];

    [selfsetUp];

    [selfloadData];

    // Do any additional setup after loading the view.

}

-(void)setUp{

_scrollView = [[UIScrollView alloc] init];

    [_scrollView setTranslatesAutoresizingMaskIntoConstraints:NO];

    _scrollView.backgroundColor = [UIColor blackColor];

    _scrollView.maximumZoomScale = 5;

    _scrollView.delegate = self;

    [self.view addSubview:_scrollView];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[scrollView]-0-|" options:kNilOptions metrics:nil views:@{@"scrollView":_scrollView}]];

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[scrollView]-0-|" options:kNilOptions metrics:nil views:@{@"scrollView":_scrollView}]];

    _imageView= [[UIImageViewalloc]init];

    [_imageView setTranslatesAutoresizingMaskIntoConstraints:NO];

    _imageView.contentMode = UIViewContentModeScaleAspectFit;//缩放显示

    _imageView.userInteractionEnabled = YES;

    [_scrollView addSubview:_imageView];

    [_scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[imageView(scrollView)]-0-|" options:kNilOptions metrics:nil views:@{@"imageView":_imageView,@"scrollView":_scrollView}]];

    [_scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[imageView(scrollView)]-0-|" options:kNilOptions metrics:nil views:@{@"imageView":_imageView,@"scrollView":_scrollView}]];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];

    [_imageView addGestureRecognizer:tap];

-(void)loadData{

    if(_image){

        _imageView.image = _image;

    }

    if(_imageUrl.length>0){

        [_imageView setImageWithURL:[NSURL URLWithString:_imageUrl]];

    }

}

-(void)dismiss{

    [self dismissViewControllerAnimated:YES completion:nil];

}

#pragma mark - UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{

    return _imageView;

}

是不是一目了然。简单粗暴,每天更新一个iOS小功能,喜欢的记得点赞加关注哦

上一篇下一篇

猜你喜欢

热点阅读