有时需要设置一个广告栏,那么用UIScrollView是再好不过了,直接上代码
1.首先在.h里面设置属性
//
// FirstViewController.h
// CyberGo
//
// Created by chenzhizheng on 15/2/6.
// Copyright (c) 2015年 KLH. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController<UIScrollViewDelegate>
{
int PageNum;
BOOL Tend;
}
@property (nonatomic,strong) UIScrollView * home_images;
@property (nonatomic,strong) UICollectionView * home_collection;
@property (nonatomic,strong) UIPageControl * home_page;
@end
2.在.m里面实现方法
//
// FirstViewController.m
// CyberGo
//
// Created by chenzhizheng on 15/2/6.
// Copyright (c) 2015年 KLH. All rights reserved.
//
#import "FirstViewController.h"
#import "Common.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"底板.jpg"]];
[self.view addSubview:[self home_images]];
[self.view addSubview:[self home_page]];
[self.view addSubview:[self home_collection]];
}
这里是UIScrollView的getter方法
-(UIScrollView *)home_images
{
if (!_home_images) {
_home_images = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 100)];
_home_images.indicatorStyle = UIScrollViewIndicatorStyleDefault;//设置滚动条风格
_home_images.showsHorizontalScrollIndicator = NO;//设置是否显示横向滚动条
_home_images.showsVerticalScrollIndicator = NO;//设置是否显示纵向滚动条
_home_images.bounces = YES;//是否具有反弹效果
_home_images.pagingEnabled = YES;//是否可滑动翻页
_home_images.contentSize = CGSizeMake(WIDTH * 3, 0);//设置UIScrollView的大小(3张图片大小)
_home_images.delegate = self;//设置代理
//视图滚动循环
for (int i =0; i < 3; i++) {
UIImageView * view = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * i, 0, WIDTH, 100)];
view.image = [UIImage imageNamed:[NSString stringWithFormat:@"滚动图%d.jpg",i+1]];
[_home_images addSubview:view];
}
//设置定时器
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(autoScrollimages:) userInfo:nil repeats:YES];
}
return _home_images;
}
-(void)autoScrollimages:(id)sender
{
if (PageNum % 3 == 0) {
if (!Tend) {
self.home_page.currentPage++;
if (self.home_page.currentPage == self.home_page.numberOfPages - 1) {
Tend = YES;
}
}else{
self.home_page.currentPage --;
if (self.home_page.currentPage == 0) {
Tend = NO;
}
}
[UIView animateWithDuration:1.0f
animations:^{
self.home_images.contentOffset = CGPointMake(self.home_page.currentPage * 320, 0);
}];
}
PageNum ++;
}
//翻页控制显示器
-(UIPageControl *)home_page
{
if (!_home_page) {
//三个点的位置及大小
_home_page = [[UIPageControl alloc] initWithFrame:CGRectMake(WIDTH * 0.75, 100 * 0.9, 40, 5)];
_home_page.numberOfPages = 3;
_home_page.currentPage = 0;//默认选中第一张展示
}
return _home_page;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end