您的位置:首页 > 产品设计 > UI/UE

IOS菜鸟的所感所思(十五)—— UIScrollView和UIPageControl的组合

2015-07-02 21:32 519 查看



目标:手势滑动界面实现图片的切换并且UIPageControl的currentPage的状态发生变化。

步聚: 1.视图的布局。

//视图关联三个组件

@property (weak,
nonatomic) IBOutlet
UIScrollView *swipeView;

@property (weak,
nonatomic) IBOutlet
UIPageControl *pageControl;

@property (strong,
nonatomic) IBOutlet
UIImageView *imageView;

//存放图片的数组

@property (nonatomic,
strong) NSMutableArray *imageArray;



2.代码的实现,

- (void)viewDidLoad {

[super
viewDidLoad];

[self
setSwipeViewProperty];

[self
getImageToArray];

[self
setPageControlProperty];
}
会调用相应的方法,

//设置UIScrollView的属性
- (void)setSwipeViewProperty{

//视图是分页的形式

_swipeView.pagingEnabled =
YES;

_swipeView.delegate =
self;

//相当于画廊的长度和高度

_swipeView.contentSize =
CGSizeMake(1920,
320);

//画廊的起点位置

_swipeView.contentOffset =
CGPointMake(0,
0);

//滑动时图片下方是否有横线

_swipeView.showsVerticalScrollIndicator =
NO;

_swipeView.showsHorizontalScrollIndicator =
NO;

//可以与用户进行交互

_swipeView.userInteractionEnabled =
YES;
}
- (void)getImageToArray{

//初始化数组

_imageArray = [[NSMutableArray
alloc]
initWithObjects:@"picture0.jpg",@"picture1.jpg",@"picture2.jpg",@"picture3.jpg",@"picture4.jpg",@"picture5.jpg",
nil];

//将每一张imageView添加到画廊中并指定每个的起始位置和宽高
[_imageArray
enumerateObjectsUsingBlock:^(NSString *obj,
NSUInteger idx, BOOL *stop) {

_imageView = [[UIImageView
alloc] initWithImage:[UIImage
imageNamed:obj]];

_imageView.frame =
CGRectMake(55+320*idx,
62, 200,
210);

_imageView.userInteractionEnabled =
YES;

[_swipeView
addSubview:_imageView];
}];
}

//设置pagecontrol的属性,有六个图片点,起始点是0
- (void)setPageControlProperty{

_pageControl.numberOfPages =
6;

_pageControl.currentPage =
0;

//点击点得时候会相应的方法

[_pageControl
addTarget:self
action:@selector(pageAction)
forControlEvents:UIControlEventValueChanged];
}
-(void)pageAction

{

NSInteger page =
_pageControl.currentPage;

NSLog(@"%ld",page);

CGRect frame = _swipeView.frame;
frame.origin.x = frame.size.width
* page;
frame.origin.y =
0;

//会弹出相应的视图

[_swipeView
scrollRectToVisible:frame animated:YES];

}
3.需要实现协议中的方法

//实现的方法,滑动后
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

int currentPage =
_swipeView.contentOffset.x /
_swipeView.frame.size.width;

NSLog(@"%f",_swipeView.frame.size.width);

NSLog(@"%d",currentPage);

//如果是第一个,也就是要开始循环到最后第一个

if (currentPage==0) {

[_swipeView
scrollRectToVisible:CGRectMake(320*6-65,
0, 200,
210)
animated:NO];

}

else if (currentPage==([_imageArray
count])-1) {

//如果是最后一个,也就是要开始循环的第一个

[_swipeView
scrollRectToVisible:CGRectMake(0,
0, 200,
210)
animated:NO];

}

}

//视图开始滑动时会响应的方法,改变点得状态
- (void)scrollViewDidScroll:(UIScrollView *)sender

{

int page = _swipeView.contentOffset.x/320;

_pageControl.currentPage = page;

}
效果:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: