我有一个内部有UIImageView的UIScrollview。当用户拖动UIScrollView时,UIImageView会动画如下:
这是我正在使用的代码,很简单:
- (void)viewDidLoad {
[super viewDidLoad];
self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
self.scrollView.delegate = self;
[self.view addSubview:self.scrollView];
self.zoomView = [[UIImageView alloc] initWithFrame:CGRectZero];
[self.scrollView addSubview:self.zoomView];
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
self.scrollView.frame = self.view.bounds;
self.scrollView.backgroundColor = [UIColor purpleColor];
self.view.backgroundColor = [UIColor yellowColor];
self.scrollView.alwaysBounceVertical = YES;
self.zoomView.frame = CGRectMake(0, 0, self.view.frame.size.width, 100);
self.zoomView.backgroundColor = [UIColor redColor];
self.zoomView.image = [UIImage imageNamed:@"Spawn.jpg"];
self.zoomView.contentMode = UIViewContentModeScaleAspectFill;
self.cachedImageViewSize = self.zoomView.frame;
}
#pragma mark - UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat y = -scrollView.contentOffset.y;
if (y < 0) {
return;
}
self.zoomView.frame = CGRectMake(0, scrollView.contentOffset.y, self.cachedImageViewSize.size.width + y, self.cachedImageViewSize.size.height + y);
self.zoomView.center = CGPointMake(self.view.center.x, self.zoomView.center.y);
}
我的问题是,如何使用autoLayout执行完全相同的效果? 我通过代码使用autolayout,就像这样,但我不知道在UIScrollView委托上添加什么:
self.zoomView.translatesAutoresizingMaskIntoConstraints = NO;
self.scrollView.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_zoomView, _scrollView);
NSMutableArray *constraint = [[NSMutableArray alloc] init];
[constraint addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_zoomView]|" options:0 metrics:nil views:viewsDictionary]];
[constraint addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_scrollView]|" options:0 metrics:nil views:viewsDictionary]];
[constraint addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_scrollView]|" options:0 metrics:nil views:viewsDictionary]];
[constraint addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_zoomView(==30)]" options:0 metrics:nil views:viewsDictionary]];
[self.view addConstraints:constraint];
似乎Autolayout对这种动画并不擅长。