使用UIScrollView实现滚屏效果

在一屏中手指滑动实现多个页面的滑动切换可使用UIScrollView来实现 @synthesize scrollView; @synthesize pageControl; // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height)]; scrollView.userInteractionEnabled = YES; scrollView.directionalLockEnabled = YES; scrollView.pagingEnabled = YES; scrollView.showsVerticalScrollIndicator = NO; scrollView.showsHorizontalScrollIndicator = NO; scrollView.delegate = self; CGRect frame = self.view.frame; frame.origin.y = 0.0f; UIView* viewFirst = [[[UIView alloc] initWithFrame:frame] autorelease]; viewFirst.backgroundColor = [UIColor greenColor]; UIImage *image =[UIImage imageNamed:@"1.jpg"]; UIImageView* imageView = [[UIImageView alloc] initWithFrame:frame]; imageView.image = image; [viewFirst addSubview:imageView]; frame.origin.x += self.view.frame.size.width; UIView* viewSecond = [[[UIView alloc] initWithFrame:frame] autorelease]; //viewSecond.backgroundColor = [UIColor blueColor]; UITextView* textView = [[[UITextView alloc] initWithFrame:self.view.frame] autorelease]; textView.text = @"\n sadfsfasdfsdf" @"sddsffsdfsdf"; [viewSecond addSubview:textView]; frame.origin.x += self.view.frame.size.width; UIView* viewThird = [[[UIView alloc] initWithFrame:frame] autorelease]; //viewThird.backgroundColor = [UIColor redColor]; UIImage *image2 =[UIImage imageNamed:@"2.jpg"]; UIImageView* imageView2 = [[UIImageView alloc] initWithFrame:self.view.frame]; imageView2.image = image2; [viewThird addSubview:imageView2]; scrollView.contentSize = CGSizeMake(self.view.frame.size.width*3, self.view.frame.size.height); [scrollView addSubview:viewFirst]; [scrollView addSubview:viewSecond]; [scrollView addSubview:viewThird]; CGSize sizePageControl = CGSizeMake(120, 40); CGRect framePageControl = CGRectMake((self.view.frame.size.width-sizePageControl.width)/2, (self.view.frame.size.height-sizePageControl.height-40), sizePageControl.width, sizePageControl.height); pageControl = [[UIPageControl alloc] initWithFrame:framePageControl]; pageControl.hidesForSinglePage = YES; pageControl.userInteractionEnabled = NO; pageControl.backgroundColor = [UIColor clearColor]; pageControl.numberOfPages = 1; [self.view addSubview:scrollView]; [self.view addSubview:pageControl]; } 同时你的ViewController 要实现UIScrollViewDelegate 协议的如下方法, 根据scroll 更新UIPageControl(当然如过你用到UIPageControl的话就无所谓了...) - (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView { int index = fabs(scrollView.contentOffset.x)/self.view.frame.size.width; pageControl.currentPage = index; }

你可能感兴趣的:(uiscrollview)