-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathYFHorizontalParallaxView.m
64 lines (55 loc) · 2.05 KB
/
YFHorizontalParallaxView.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// YFHorizontalParallaxView.m
// YFHorizontalParallaxView
//
// Created by Yang Fei on 13-2-21.
// Copyright (c) 2013年 Yang Fei. All rights reserved.
//
#import "YFHorizontalParallaxView.h"
@interface YFHorizontalParallaxView () <UIScrollViewDelegate>
@property (nonatomic, strong) NSMutableArray *scrollViewArray;
@end
@implementation YFHorizontalParallaxView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)dealloc{
[[_scrollViewArray lastObject] removeObserver:self forKeyPath:@"contentOffset"];
}
- (id)initWithFrame:(CGRect)frame views:(NSArray *)views
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
_scrollViewArray = [NSMutableArray array];
for (UIView *view in views) {
UIScrollView *sv = [[UIScrollView alloc] initWithFrame:self.bounds];
sv.delegate = self;
sv.contentSize = view.frame.size;
[sv addSubview:view];
[self addSubview:sv];
[_scrollViewArray addObject:sv];
}
[[_scrollViewArray lastObject] addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}
return self;
}
- (void)updateViewsContentOffsetByPercent:(float)percent{
for (int i=0; i<[_scrollViewArray count]-1; i++) {
UIScrollView *sv = [_scrollViewArray objectAtIndex:i];
sv.contentOffset = CGPointMake(percent*(sv.contentSize.width-sv.frame.size.width), sv.contentOffset.y);
}
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if(![keyPath isEqualToString:@"contentOffset"]) return;
CGPoint offset = [[change objectForKey:@"new"] CGPointValue];
UIScrollView *foregroundScrollView = [_scrollViewArray lastObject];
float percent = offset.x/(foregroundScrollView.contentSize.width-foregroundScrollView.frame.size.width);
[self updateViewsContentOffsetByPercent:percent];
}
@end