iOS開發UI篇—UIScrollView控件實現圖片輪播佈局
1、實現效果atom
實現圖片的自動輪播spa
2、實現代碼3d
storyboard中佈局code
代碼:orm
#import "YYViewController.h"blog
@interface YYViewController () <UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
/**
* 頁碼
*/
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;圖片
@property (nonatomic, strong) NSTimer *timer;
@end開發
@implementation YYViewControllerrem
- (void)viewDidLoad
{
[super viewDidLoad];
// 圖片的寬
CGFloat imageW = self.scrollview.frame.size.width;
// CGFloat imageW = 300;
// 圖片高
CGFloat imageH = self.scrollview.frame.size.height;
// 圖片的Y
CGFloat imageY = 0;
// 圖片中數
NSInteger totalCount = 5;
// 1.添加5張圖片
for (int i = 0; i < totalCount; i++) {
UIImageView *imageView = [[UIImageView alloc] init];
// 圖片X
CGFloat imageX = i * imageW;
// 設置frame
imageView.frame = CGRectMake(imageX, imageY, imageW, imageH);
// 設置圖片
NSString *name = [NSString stringWithFormat:@"img_0%d", i + 1];
imageView.image = [UIImage imageNamed:name];
// 隱藏指示條
self.scrollview.showsHorizontalScrollIndicator = NO;
[self.scrollview addSubview:imageView];
}
// 2.設置scrollview的滾動範圍
CGFloat contentW = totalCount *imageW;
//不容許在垂直方向上進行滾動
self.scrollview.contentSize = CGSizeMake(contentW, 0);
// 3.設置分頁
self.scrollview.pagingEnabled = YES;
// 4.監聽scrollview的滾動
self.scrollview.delegate = self;
[self addTimer];
}
- (void)nextImage
{
int page = (int)self.pageControl.currentPage;
if (page == 4) {
page = 0;
}else
{
page++;
}
// 滾動scrollview
CGFloat x = page * self.scrollview.frame.size.width;
self.scrollview.contentOffset = CGPointMake(x, 0);
}
// scrollview滾動的時候調用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
NSLog(@"滾動中");
// 計算頁碼
// 頁碼 = (contentoffset.x + scrollView一半寬度)/scrollView寬度
CGFloat scrollviewW = scrollView.frame.size.width;
CGFloat x = scrollView.contentOffset.x;
int page = (x + scrollviewW / 2) / scrollviewW;
self.pageControl.currentPage = page;
}
// 開始拖拽的時候調用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
// 關閉定時器(注意點; 定時器一旦被關閉,沒法再開啓)
// [self.timer invalidate];
[self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
// 開啓定時器
[self addTimer];
}
/**
* 開啓定時器
*/
- (void)addTimer{
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
106 }
/**
* 關閉定時器
*/
- (void)removeTimer
{
[self.timer invalidate];
}
@end
提示:如下兩個屬性已經和storyboard中的控件進行了連線。
@property (weak, nonatomic) IBOutletUIScrollView *scrollview;
@property (weak, nonatomic) IBOutletUIPageControl *pageControl;
補充:定時器NSTimer
定時器 適合用來隔一段時間作一些間隔比較長的操做
NSTimeInterval:多長多件操做一次
target :操做誰
selector : 要操做的方法
userInfo: 傳遞參數
repeats: 是否重複
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];