随笔
scrollview的应用
@interface ViewController ()<UIScrollViewDelegate>
@property (nonatomic,assign) CGFloat itemWidth;
@property (nonatomic,assign) CGFloat offset;
@property (nonatomic,assign) CGFloat screenWidth;
@property (nonatomic,assign) CGFloat contentSizeWidth;
@property (nonatomic,assign) CGFloat position;
@end
- (void)viewDidLoad {
[super viewDidLoad];
CGFloatscreenWidth = [UIScreenmainScreen].bounds.size.width;
self.screenWidth= screenWidth;
CGFloatscrollX =0;
CGFloatscrollW = screenWidth -2* scrollX;
UIScrollView*scrollview = [[UIScrollViewalloc]initWithFrame:CGRectMake(scrollX ,100, scrollW,50)];
scrollview.delegate=self;
scrollview.bounces=NO;
scrollview.showsVerticalScrollIndicator = NO;
scrollview.showsHorizontalScrollIndicator = NO;
scrollview.backgroundColor = [UIColor redColor];
[self.viewaddSubview:scrollview];
CGFloattargetViewX =0;
CGFloattargetViewY =0;
CGFloattargetViewW =300;
CGFloattargetViewH =50;
UIView*targetView = [[UIViewalloc]initWithFrame:CGRectMake(targetViewX, targetViewY, targetViewW, targetViewH)];
targetView.backgroundColor = UIColor.blueColor;
[scrollviewaddSubview:targetView];
self.itemWidth= targetViewW;
UIView*lineView = [[UIViewalloc]initWithFrame:CGRectMake(screenWidth/2.0-1,95,2,60)];
lineView.backgroundColor = [UIColor greenColor];
[self.viewaddSubview:lineView];
CGFloatcontentSizeWidth =2* targetViewW + scrollW;
self.contentSizeWidth= contentSizeWidth;
scrollview.contentSize=CGSizeMake(contentSizeWidth, targetViewH);
scrollview.contentOffset=CGPointMake(contentSizeWidth/2.0- screenWidth/2.0,0);
CGFloatoffSet = 800;
if(offSet <0) {
offSet =0;
}elseif(offSet > self.itemWidth){
offSet =self.itemWidth;
}
self.offset= offSet;
targetViewX = contentSizeWidth/2- offSet;
targetView.frame=CGRectMake(targetViewX, targetViewY, targetViewW, targetViewH);
UIView*blackView = [[UIViewalloc]initWithFrame:CGRectMake(contentSizeWidth/2.0,0,2,50)];
blackView.backgroundColor = [UIColor blackColor];
[scrollviewaddSubview:blackView];
UIView*lineView2 = [[UIViewalloc]initWithFrame:CGRectMake(0,25, scrollview.contentSize.width,3)];
lineView2.backgroundColor = UIColor.whiteColor;
NSLog(@"--scrollview.contentSize.width---%f",scrollview.contentSize.width);
NSLog(@"--scrollview.contentSize.width---%f",scrollview.contentOffset.x);
[scrollviewaddSubview:lineView2];
}
- (void)scrollViewDidScroll:(UIScrollView*)scrollView{
NSLog(@"----%lf",scrollView.contentOffset.x);
if(scrollView.contentOffset.x<=self.itemWidth-self.offset) {
scrollView.contentOffset=CGPointMake(self.itemWidth-self.offset,0);
}elseif(scrollView.contentOffset.x> ((self.contentSizeWidth-self.screenWidth)/2.0+self.itemWidth-self.offset)){
scrollView.contentOffset=CGPointMake((self.contentSizeWidth/2.0-self.screenWidth/2.0+self.itemWidth-self.offset),0);
}
self.position= scrollView.contentOffset.x;
}
网友评论