使用iCarousel的旋转木马效果请求图片
https://github.com/nicklockwood/iCarousel
先看看效果:
源码如下:
//
// RootViewController.m
//
// Created by YouXianMing on 14-5-16.
// Copyright (c) 2014年 Y.X. All rights reserved.
//
#import "RootViewController.h"
#import "iCarousel.h"
#import "YXJSON.h"
#import "YXGCD.h"
#import "SDWebImage.h"
// 数据源
#define SOURCE_DATA @"http://www.duitang.com/album/1733789/masn/p/0/50/"
@interface RootViewController ()<iCarouselDataSource, iCarouselDelegate>
@property (nonatomic, strong) iCarousel *carousel; // iCarousel
@property (nonatomic, strong) NSMutableArray *dataArray; // 数据源
@end
@implementation RootViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// 初始化数据源
_dataArray = [[NSMutableArray alloc] init];
// 初始化iCarousel
self.carousel = [[iCarousel alloc] initWithFrame:self.view.bounds];
[self.view addSubview:_carousel];
_carousel.backgroundColor = [UIColor blackColor];
_carousel.type = iCarouselTypeWheel;
// 设置代理
self.carousel.delegate = self;
self.carousel.dataSource = self;
// 异步加载数据
[[GCDQueue globalQueue] execute:^{
// 获取json数据
NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:SOURCE_DATA]];
// 转换为字典
NSDictionary *dataDic = [YXJSON dictionaryOrArrayWithJSONSData:data];
if (dataDic)
{
NSArray *dataArray = dataDic[@"data"][@"blogs"];
for (NSDictionary *dic in dataArray)
{
NSLog(@"%@", dic[@"isrc"]);
// 存储数据
[_dataArray addObject:dic[@"isrc"]];
}
}
// 主线程更新
[[GCDQueue mainQueue] execute:^{
// 重新加载carousel
[_carousel reloadData];
}];
}];
}
#pragma mark -
#pragma mark iCarousel methods
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
// 元素个数
return [_dataArray count];
}
- (UIView *)carousel:(iCarousel *)carousel
viewForItemAtIndex:(NSUInteger)index // view的标志
reusingView:(UIView *)view // 重用的view
{
if (view == nil)
{
view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300.0f, 400.0f)];
}
// 强行转换指针
UIImageView *pointView = (UIImageView *)view;
// 使用SDWebImage异步下载图片
[pointView setImageWithURL:[NSURL URLWithString:_dataArray[index]]];
// 图片自动适应
pointView.contentMode = UIViewContentModeScaleAspectFit;
return view;
}
- (CGFloat)carousel:(iCarousel *)carousel
valueForOption:(iCarouselOption)option
withDefault:(CGFloat)value
{
if (option == iCarouselOptionSpacing)
{
return value * 1.1f;
}
return value;
}
@end
RootViewController.m
以下几个地方使用了本人自己封装的类,不开源,看官请自行替换相关方法-_-!
核心的地方如下:
so easy :)
问:如何实现view的点击事件?
实现协议方法 - (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index; 即可
问:如何获取偏移量?
实现协议,然后如下使用
- (void)carouselDidScroll:(iCarousel *)carousel
{
NSLog(@"scrollOffset %f", carousel.scrollOffset);
}
时间: 2024-11-16 15:22:34