需求:
1.点击卡片跳至中心
2.若点击的卡片已在中心,跳转控制器
3.滑动卡片至中心
实现效果:
iCarousel效果图.gif
具体实现:
遵守协议
@interface AXView () <iCarouselDelegate, iCarouselDataSource>
@property (nonatomic, strong) iCarousel *crousel;
// 单元格
@property (nonatomic, strong) AXViewItem *item;
@end
初始化
_carousel = [[iCarousel alloc] initWithFrame:self.bounds];
// 设置滚动的模式
_carousel.type = iCarouselTypeRotary;
// _carousel.scrollOffset = -100;
// 设置手势滑动的力度 deault 0.95
_carousel.decelerationRate = 0.5;
_carousel.delegate = self;
_carousel.dataSource = self;
[self addSubview:_carousel];
数据源方法
#pragma mark iCarouselDataSource
// 有多少项
- (NSInteger)numberOfItemsInCarousel:(iCarousel *)carousel{
// 这里返回网络获取的数据数组个数
return 3;
}
// 最大有多少个可以显示
- (NSUInteger)numberOfVisibleItemsInCarousel:(iCarousel *)carousel{
return 5;
}
//每一个的内容
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view{
AXViewItem *item = nil;
if (!view) {
view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScaleWidth(100),ScaleHeight(150))];
item = [[AXViewItem alloc]initWithFrame:view.bounds];
[view addSubview:item];
item.tag = 100;
}
item = (AXViewItem *)[view viewWithTag:100];
self.item = item;
// 模型赋值
// ...
return item;
}
代理方法
#pragma mark - iCarouselDelegate
// MARK :返回的宽度值是单元格item的可操作范围
-(CGFloat)carouselItemWidth:(iCarousel *)carousel{
return ScaleWidth(79);
}
// 设置布局的选项:此处只用到下面两种
- (CGFloat)carousel:(iCarousel *)carousel valueForOption:(iCarouselOption)option withDefault:(CGFloat)value{
switch (option)
{
case iCarouselOptionWrap:
{
// 是否旋转木马效果
return YES;
}
case iCarouselOptionSpacing:
{
// 旋转半径,默认为0.25
return value * 4.0f;
}
default:
{
return value;
}
}
}
didselect方法和拖拽结束时的方法单独抽离出来
- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index{
// if (self.model.count > 0) {
// Model *a = self.model[index];
// self.item.model = a;
// }
if ( index == _ carousel.currentItemIndex) {
// 因为多是view跳转控制器,所以此处用跟、根控制器为tabbarController演示
UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController.rootViewController[0];
AXTestViewController *vc = [[AXTestViewController alloc]init];
[nav pushViewController:vc animated:YES];
}
// 测试用
switch (index) {
case 0:
{
NSLog(@"0======currentItemIndex:%ld",(long)carousel.currentItemIndex);
}
break;
case 1:
{
NSLog(@"1======currentItemIndex:%ld",(long)carousel.currentItemIndex);
}
break;
case 2:
{
NSLog(@"2======currentItemIndex:%ld",(long)carousel.currentItemIndex);
}
break;
default:
break;
}
}
// 这个注释省略
- (void)carouselDidEndDecelerating:(iCarousel *)carousel{
// 获取当前index
// 模型赋值刷新控件等
// 发送通知
}
最后销毁
- (void)dealloc
{
//it's a good idea to set these to nil here to avoid
//sending messages to a deallocated viewcontroller
_carousel.delegate = nil;
_carousel.dataSource = nil;
}