当前位置:编程学习 > wap >>

iOS -UIScrollView-展示多张图片

(1)申明
 
 
[objc]  
@inte易做图ce ViewController : UIViewController <UIScrollViewDelegate>{  
  
    UIScrollView *imageScrollView;  
    UIPageControl *pageControl;  
  
      
}  
  
@end  
 
(2)
 
[objc]  
//添加UIScrollView  
-(void)addScrollView {  
      
    imageScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(150, 150, 520, 325)];  
    imageScrollView.backgroundColor = [UIColor clearColor];  
    imageScrollView.contentSize = CGSizeMake(520*7, 325);    // 设置内容大小  
    imageScrollView.delegate = self;  
    imageScrollView.pagingEnabled = YES;  
    imageScrollView.showsHorizontalScrollIndicator = NO;//滚动的时候是否有水平的滚动条,默认是有的  
  
  
  
    int a = 0;  
    for (int i = 0; i < 7; i++) {  
          
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0+a, 0, 520, 325)];  
        imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png",i]];  
        imageView.tag = 110 + i;  
        imageView.userInteractionEnabled=YES;//与用户交互  
        [imageScrollView addSubview:imageView];  
          
          //为UIImageView添加点击手势  
        UITapGestureRecognizer *tap;  
        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];  
        tap.numberOfTapsRequired = 1;//tap次数  
        tap.numberOfTouchesRequired = 1;//手指数  
        [imageView addGestureRecognizer:tap];  
  
        a += 520;  
    }  
      
    [self.view addSubview:imageScrollView];  
}  
  
//添加PageControl  
-(void) addPageControl {  
      
    pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(768/2-150, 440, 320, 40)];  
    pageControl.numberOfPages = 7;//页数(几个圆圈)  
    pageControl.tag = 101;  
    pageControl.currentPage = 0;  
  
    [self.view addSubview:pageControl];  
  
}  
  
//单击图片之后响应的  
-(void) tap: (UITapGestureRecognizer*)sender{  
      
    NSLog(@"tap %ld image",(long)pageControl.currentPage);  
  
}  
  
//滚动视图的代理方法- scrollview 减速停止  
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {  
  
    int current = scrollView.contentOffset.x/400;  
    NSLog(@"current:%d",current);  
    pageControl.currentPage = current;  
}  
 
(3)
 
[objc]  
- (void)viewDidLoad  
{  
    [super viewDidLoad];  
    // Do any additional setup after loading the view, typically from a nib.  
    self.view.backgroundColor = [UIColor cyanColor];  
    [self addScrollView];  
    [self addPageControl];  
}  
 
效果图:
 
 
 
--
 
之前有个这个警告
 
 
原因:这个方法的参数scrollView跟我定义的UIScrollView *scrollView同名。把自己定义的
 
UIScrollView 名字改了就可以拉。。
 
补充:移动开发 , IOS ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,