//
// ViewController.m
// OCPrograming
//
// Created by zhoushijie on 2018/12/10.
// Copyright © 2018 zhoushijie. All rights reserved.
//
#import "ViewController1.h"
#define screenWidth UIScreen.mainScreen.bounds.size.width
@interface ViewController1 () <UIScrollViewDelegate>
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UIView *slideView;
@property (nonatomic, copy) NSArray <UIView *> *imgArr;
@end
@implementation ViewController1
- (UIScrollView *)scrollView {
if (_scrollView == nil) {
_scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 80, screenWidth, 100)];
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.alwaysBounceVertical = NO;
_scrollView.bounces = NO;
_scrollView.contentSize = CGSizeMake(screenWidth * 2, 100);
_scrollView.pagingEnabled = YES;
_scrollView.backgroundColor = [UIColor redColor];
_scrollView.delegate = self;
_scrollView.contentOffset = CGPointMake(0, 0);
_scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
// [_scrollView setContentOffset:CGPointZero];
[_scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}
return _scrollView;
}
- (UIView *)bgView {
if (_bgView == nil) {
_bgView = [[UIView alloc] initWithFrame:CGRectMake(120, 250, 100, 50)];
_bgView.backgroundColor = [UIColor grayColor];
}
return _bgView;
}
- (UIView *)slideView {
if (_slideView == nil) {
_slideView = [[UIView alloc] initWithFrame:CGRectZero];
_slideView.backgroundColor = [UIColor redColor];
}
return _slideView;
}
- (NSArray<UIView *> *)imgArr {
if (_imgArr == nil) {
NSMutableArray *tempArr = [NSMutableArray array];
UIView *view1 = [[UIView alloc] initWithFrame:CGRectZero];
view1.backgroundColor = [UIColor blueColor];
[tempArr addObject:view1];
UIView *view2 = [[UIView alloc] initWithFrame:CGRectZero];
view2.backgroundColor = [UIColor yellowColor];
[tempArr addObject:view2];
_imgArr = tempArr;
}
return _imgArr;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self createView];
}
- (void)createView {
[self.view addSubview:self.scrollView];
for (int i = 0; i < 2; i++) {
UIView *view = self.imgArr[i];
view.frame = CGRectMake(i * screenWidth, 0, screenWidth, 100);
[self.scrollView addSubview:view];
}
[self.view addSubview:self.bgView];
[self.bgView addSubview:self.slideView];
self.slideView.frame = CGRectMake(0, 0, 50, 50);
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"contentOffset"]) {
CGFloat offsetX = [[change objectForKey:@"new"] CGPointValue].x;
double proportion = (double)(offsetX / screenWidth);
CGFloat needOffset = proportion * 50;
[UIView animateWithDuration:0.001 animations:^{
CGRect tempFrame = self.slideView.frame;
tempFrame.origin.x = needOffset;
self.slideView.frame = tempFrame;
}];
}
}
@end