美文网首页
OC 滚动视图

OC 滚动视图

作者: J_mine | 来源:发表于2017-07-27 21:14 被阅读0次

滚动视图现在应用于各大App,是十分必要的一种功能,做滚动视图我们要用到UIScrollView控件,这篇文章就对滚动视图做出阐述

1 我们要先创建第二个页面 用作跳转,并在viewController中导入头文件

#import "ViewController.h"
#import "one.h"

2 创建全局变量方便以后的使用,并设置代理协议

@interface ViewController ()<UIScrollViewDelegate>
{
    UIScrollView * theScroll;
    NSArray * theArr;
    UIPageControl * thePage;
}
   此处用数组来存储图片
   thePage 做滚动视图的页码

3 在viewcontroller中实现具体的代码

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化一个滚动视图
    theScroll = [[UIScrollView alloc]initWithFrame:self.view.frame];
    //设置代理
    theScroll.delegate = self;
    //设置按页滚动
    theScroll.pagingEnabled = YES;
    //设置是否显示滚动条
    theScroll.showsHorizontalScrollIndicator = NO;
    //加载
    [self.view addSubview:theScroll];
    
    theArr = @[@"1.jpg",@"2.jpg",@"3.jpg"];
    
    CGFloat x = 0.0;
    
    for (int i = 0; i < theArr.count; i++) {
        UIImageView * theImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, 0, self.view.frame.size.width, self.view.frame.size.height)];
        theImageView.image = [UIImage imageNamed:theArr[i]];
        x = x+self.view.frame.size.width;
        [theScroll addSubview:theImageView];
        
        if(i==theArr.count -1)
        {
            UIButton *but=[[UIButton alloc]initWithFrame:CGRectMake((self.view.frame.size.width -100)/2, 550, 100, 40)];
            [but setTitle:@"立即体验" forState:UIControlStateNormal];
            [but setBackgroundColor:[UIColor colorWithRed:29/250.0 green:170/250.0 blue:230/250.0 alpha:1.0]];
            [but addTarget:self action:@selector(tz) forControlEvents:UIControlEventTouchUpInside];
            but.layer.cornerRadius=10;
            but.layer.masksToBounds=YES;
            theImageView.userInteractionEnabled=YES;
            [theImageView addSubview:but];
        }
    }
    theScroll.contentSize = CGSizeMake(x, self.view.frame.size.height);
    
    //初始化一个分页控制器
    thePage = [[UIPageControl alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-30, self.view.frame.size.height/5*4, 60, 20)];
    //设置分页控制器的个数
    thePage.numberOfPages = theArr.count;
    //设置分页控制器的颜色
    thePage.pageIndicatorTintColor = [UIColor grayColor];
    //设置分页控制器选中时的颜色
    thePage.currentPageIndicatorTintColor = [UIColor redColor];
    //加载
    [self.view addSubview:thePage];
    
}

接着 我们实现分页控制器和滚动视图的关联

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    thePage.currentPage = theScroll.contentOffset.x/self.view.frame.size.width;
}

最后 实现按钮的跳转方法 ,此处要用到之前所创建的第二个视图

-(void)tz
{
    one *v1=[one new];
    [self presentViewController:v1 animated:YES completion:^{}];
}

相关文章

网友评论

      本文标题:OC 滚动视图

      本文链接:https://www.haomeiwen.com/subject/veetlxtx.html