Ios 如何使用collectionView自动滑动图像
我想用Ios 如何使用collectionView自动滑动图像,ios,objective-c,iphone,xcode7,autoscroll,Ios,Objective C,Iphone,Xcode7,Autoscroll,我想用UICollectionView创建幻灯片。现在我创建了一个集合视图和一个自定义单元格。我正在显示所有图像,但不是自动滚动。所以我想,当视图控制器加载时,集合视图的所有单元格都应该自动滚动,即使按下滑动按钮。但是我搜索了所有的文件,但是没有找到。所以,请给任何想法或给我任何教程链接也 我为UICollectionView实现了一个简单的自动滚动组件,您可以从这里获得-。 我已经在下面包含了您需要的原始代码: Swift 3.0+: @IBOutlet weak var collec
UICollectionView
创建幻灯片。现在我创建了一个集合视图和一个自定义单元格。我正在显示所有图像,但不是自动滚动。所以我想,当视图控制器加载时,集合视图的所有单元格都应该自动滚动,即使按下滑动按钮。但是我搜索了所有的文件,但是没有找到。所以,请给任何想法或给我任何教程链接也 我为UICollectionView
实现了一个简单的自动滚动组件,您可以从这里获得-。
我已经在下面包含了您需要的原始代码:Swift 3.0+:
@IBOutlet weak var collectionView: UICollectionView!
var timer:Timer? = nil
var datasource: [UIImage]?
@IBAction func previousButtonAction(sender: UIButton) {
if self.datasource != nil {
if self.datasource?.count != 0 {
self.scrollToPreviousOrNextCell(direction: "Previous")
}
}
}
@IBAction func nextButtonAction(sender: UIButton) {
if self.datasource != nil {
if self.datasource?.count != 0 {
self.scrollToPreviousOrNextCell(direction: "Next")
}
}
}
@IBAction func pauseButtonAction(sender: UIButton) {
self.timer.invalidate()
}
//After you've received data from server or you are ready with the datasource, call this method. Magic!
func reloadCollectionView() {
self.collectionView.reloadData()
// Invalidating timer for safety reasons
self.timer?.invalidate()
// Below, for each 3.5 seconds MyViewController's 'autoScrollImageSlider' would be fired
self.timer = Timer.scheduledTimer(timeInterval: 3.5, target: self, selector: #selector(MyViewController.autoScrollImageSlider), userInfo: nil, repeats: true)
//This will register the timer to the main run loop
RunLoop.main.add(self.timer!, forMode: .commonModes)
}
func scrollToPreviousOrNextCell(direction: String) {
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.async {
let firstIndex = 0
let lastIndex = (self.datasource?.count)! - 1
let visibleIndices = self.collectionView.indexPathsForVisibleItems
let nextIndex = visibleIndices[0].row + 1
let previousIndex = visibleIndices[0].row - 1
let nextIndexPath: IndexPath = IndexPath.init(item: nextIndex, section: 0)
let previousIndexPath: IndexPath = IndexPath.init(item: previousIndex, section: 0)
if direction == "Previous" {
if previousIndex < firstIndex {
} else {
self.collectionView.scrollToItem(at: previousIndexPath, at: .centeredHorizontally, animated: true)
}
} else if direction == "Next" {
if nextIndex > lastIndex {
} else {
self.collectionView.scrollToItem(at: nextIndexPath, at: .centeredHorizontally, animated: true)
}
}
}
}
}
func autoScrollImageSlider() {
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.async {
let firstIndex = 0
let lastIndex = (self.datasource?.count)! - 1
let visibleIndices = self.collectionView.indexPathsForVisibleItems
let nextIndex = visibleIndices[0].row + 1
let nextIndexPath: IndexPath = IndexPath.init(item: nextIndex, section: 0)
let firstIndexPath: IndexPath = IndexPath.init(item: firstIndex, section: 0)
if nextIndex > lastIndex {
self.collectionView.scrollToItem(at: firstIndexPath, at: .centeredHorizontally, animated: true)
} else {
self.collectionView.scrollToItem(at: nextIndexPath, at: .centeredHorizontally, animated: true)
}
}
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellId = "cell"
//Use your custom cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! UICollectionViewCell
cell.imageView.image = self.datasource[indexPath.row]
return cell
}
//Make sure you invalidate the timer here
override func viewWillDisappear(_ animated: Bool) { self.timer?.invalidate() }
@interface MyViewController () <UICollectionViewDelegate, UICollectionViewDataSource> {
NSTimer *timer;
NSMutableArray *datasource;
}
@property (nonatomic, weak) IBOutlet UICollectionView *collectionView;
@end
@implementation MyViewController
- (IBAction)previousButtonAction:(UIButton *)sender {
if (datasource != nil) {
if (datasource.count != 0) {
[self scrollToPreviousOrNextCell:@"Previous"];
}
}
}
- (IBAction)nextButtonAction:(UIButton *)sender {
if (datasource != nil) {
if (datasource.count != 0) {
[self scrollToPreviousOrNextCell:@"Next"];
}
}
}
- (IBAction)pauseButtonAction:(UIButton *)sender { [timer invalidate]; }
//After you've received data from server or you are ready with the datasource, call this method. Magic!
- (void) reloadCollectionView {
[self.collectionView reloadData];
// Invalidating timer for safety reasons
[timer invalidate];
// Below, for each 3.5 seconds MyViewController's 'autoScrollImageSlider' would be fired
timer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(autoScrollImageSlider) userInfo:nil repeats:YES];
//This will register the timer to the main run loop
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
- (void)scrollToPreviousOrNextCell:(NSString *)direction {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
NSInteger firstIndex = 0;
NSInteger lastIndex = datasource.count - 1;
NSArray *visibleIndices = [self.collectionView indexPathsForVisibleItems];
NSInteger nextIndex = [[visibleIndices objectAtIndex:0] row] + 1;
NSInteger previousIndex = [[visibleIndices objectAtIndex:0] row] - 1;
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForRow:nextIndex inSection:0];
NSIndexPath *previousIndexPath = [NSIndexPath indexPathForRow:previousIndex inSection:0];
if ([direction isEqualToString:@"Previous"]) {
if (previousIndex < firstIndex) {
} else {
[self.collectionView scrollToItemAtIndexPath:previousIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
} else if ([direction isEqualToString:@"Next"]) {
if (nextIndex > lastIndex) {
} else {
[self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
}
});
}
-(void) autoScrollImageSlider {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
NSInteger firstIndex = 0;
NSInteger lastIndex = datasource.count - 1;
NSArray *visibleIndices = [self.collectionView indexPathsForVisibleItems];
NSInteger nextIndex = [[visibleIndices objectAtIndex:0] row] + 1;
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForRow:nextIndex inSection:0];
NSIndexPath *firstIndexPath = [NSIndexPath indexPathForRow:firstIndex inSection:0];
if (nextIndex > lastIndex) {
[self.collectionView scrollToItemAtIndexPath:firstIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
} else {
[self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
});
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellId = @"cell";
//Use your custom cell
UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
cell.imageView.image = [datasource objectAtIndex:[indexPath row]];
return cell;
}
//Make sure you invalidate the timer here
-(void)viewWillDisappear:(BOOL)animated { [timer invalidate]; }
@IBOutlet弱var collectionView:UICollectionView!
变量计时器:计时器?=无
变量数据源:[UIImage]?
@iAction func previousButtonAction(发送方:UIButton){
如果self.datasource!=nil{
如果self.datasource?.count!=0{
self.scrollToPreviousOrNextCell(方向:“上一个”)
}
}
}
@iAction func NextButtoAction(发送方:UIButton){
如果self.datasource!=nil{
如果self.datasource?.count!=0{
self.scrollToPreviousOrNextCell(方向:“下一步”)
}
}
}
@iAction func pauseButtonAction(发送方:UIButton){
self.timer.invalidate()
}
//从服务器接收数据或准备好数据源后,调用此方法。魔术
func reloadCollectionView(){
self.collectionView.reloadData()
//出于安全原因使计时器失效
self.timer?.invalidate()
//下面,MyViewController的“autoScrollImageSlider”每3.5秒就会触发一次
self.timer=timer.scheduledTimer(时间间隔:3.5,目标:self,选择器:#选择器(MyViewController.autoscrollimagesslider),userInfo:nil,repeats:true)
//这将向主运行循环注册计时器
RunLoop.main.add(self.timer!,forMode:.commonModes)
}
func scrollToPreviousOrNextCell(方向:字符串){
DispatchQueue.global(qos:.background).async{
DispatchQueue.main.async{
设firstIndex=0
让lastIndex=(self.datasource?.count)!-1
让VisibleIndex=self.collectionView.indexPathsForVisibleItems
设nextIndex=VisibleIndex[0]。行+1
让previousIndex=VisibleIndex[0]。行-1
让nextIndexPath:IndexPath=IndexPath.init(项:nextIndex,节:0)
让previousIndexPath:IndexPath=IndexPath.init(项:previousIndex,节:0)
如果方向==“上一个”{
如果上一个索引<第一个索引{
}否则{
self.collectionView.scrollToItem(位于:previousIndexPath,位于:.Centered水平,动画:true)
}
}如果方向==“下一步”,则为else{
如果nextIndex>lastIndex{
}否则{
self.collectionView.scrollToItem(位于:nextIndexPath,位于:。水平居中,动画:true)
}
}
}
}
}
func autoScrollImageSlider(){
DispatchQueue.global(qos:.background).async{
DispatchQueue.main.async{
设firstIndex=0
让lastIndex=(self.datasource?.count)!-1
让VisibleIndex=self.collectionView.indexPathsForVisibleItems
设nextIndex=VisibleIndex[0]。行+1
让nextIndexPath:IndexPath=IndexPath.init(项:nextIndex,节:0)
让firstIndexPath:IndexPath=IndexPath.init(项:firstIndex,节:0)
如果nextIndex>lastIndex{
self.collectionView.scrollToItem(at:firstIndexPath,at:.Centered水平,动画:true)
}否则{
self.collectionView.scrollToItem(位于:nextIndexPath,位于:。水平居中,动画:true)
}
}
}
}
func collectionView(collectionView:UICollectionView,cellForItemAt indexPath:indexPath)->UICollectionViewCell{
let cellId=“cell”
//使用自定义单元格
让cell=collectionView.dequeueReusableCell(withReuseIdentifier:cellId,for:indexPath)作为!UICollectionViewCell
cell.imageView.image=self.datasource[indexPath.row]
返回单元
}
//确保在此处使计时器无效
override func VIEWWILLOVERE(uu动画:Bool){self.timer?.invalidate()}
目标C:
@IBOutlet weak var collectionView: UICollectionView!
var timer:Timer? = nil
var datasource: [UIImage]?
@IBAction func previousButtonAction(sender: UIButton) {
if self.datasource != nil {
if self.datasource?.count != 0 {
self.scrollToPreviousOrNextCell(direction: "Previous")
}
}
}
@IBAction func nextButtonAction(sender: UIButton) {
if self.datasource != nil {
if self.datasource?.count != 0 {
self.scrollToPreviousOrNextCell(direction: "Next")
}
}
}
@IBAction func pauseButtonAction(sender: UIButton) {
self.timer.invalidate()
}
//After you've received data from server or you are ready with the datasource, call this method. Magic!
func reloadCollectionView() {
self.collectionView.reloadData()
// Invalidating timer for safety reasons
self.timer?.invalidate()
// Below, for each 3.5 seconds MyViewController's 'autoScrollImageSlider' would be fired
self.timer = Timer.scheduledTimer(timeInterval: 3.5, target: self, selector: #selector(MyViewController.autoScrollImageSlider), userInfo: nil, repeats: true)
//This will register the timer to the main run loop
RunLoop.main.add(self.timer!, forMode: .commonModes)
}
func scrollToPreviousOrNextCell(direction: String) {
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.async {
let firstIndex = 0
let lastIndex = (self.datasource?.count)! - 1
let visibleIndices = self.collectionView.indexPathsForVisibleItems
let nextIndex = visibleIndices[0].row + 1
let previousIndex = visibleIndices[0].row - 1
let nextIndexPath: IndexPath = IndexPath.init(item: nextIndex, section: 0)
let previousIndexPath: IndexPath = IndexPath.init(item: previousIndex, section: 0)
if direction == "Previous" {
if previousIndex < firstIndex {
} else {
self.collectionView.scrollToItem(at: previousIndexPath, at: .centeredHorizontally, animated: true)
}
} else if direction == "Next" {
if nextIndex > lastIndex {
} else {
self.collectionView.scrollToItem(at: nextIndexPath, at: .centeredHorizontally, animated: true)
}
}
}
}
}
func autoScrollImageSlider() {
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.async {
let firstIndex = 0
let lastIndex = (self.datasource?.count)! - 1
let visibleIndices = self.collectionView.indexPathsForVisibleItems
let nextIndex = visibleIndices[0].row + 1
let nextIndexPath: IndexPath = IndexPath.init(item: nextIndex, section: 0)
let firstIndexPath: IndexPath = IndexPath.init(item: firstIndex, section: 0)
if nextIndex > lastIndex {
self.collectionView.scrollToItem(at: firstIndexPath, at: .centeredHorizontally, animated: true)
} else {
self.collectionView.scrollToItem(at: nextIndexPath, at: .centeredHorizontally, animated: true)
}
}
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellId = "cell"
//Use your custom cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! UICollectionViewCell
cell.imageView.image = self.datasource[indexPath.row]
return cell
}
//Make sure you invalidate the timer here
override func viewWillDisappear(_ animated: Bool) { self.timer?.invalidate() }
@interface MyViewController () <UICollectionViewDelegate, UICollectionViewDataSource> {
NSTimer *timer;
NSMutableArray *datasource;
}
@property (nonatomic, weak) IBOutlet UICollectionView *collectionView;
@end
@implementation MyViewController
- (IBAction)previousButtonAction:(UIButton *)sender {
if (datasource != nil) {
if (datasource.count != 0) {
[self scrollToPreviousOrNextCell:@"Previous"];
}
}
}
- (IBAction)nextButtonAction:(UIButton *)sender {
if (datasource != nil) {
if (datasource.count != 0) {
[self scrollToPreviousOrNextCell:@"Next"];
}
}
}
- (IBAction)pauseButtonAction:(UIButton *)sender { [timer invalidate]; }
//After you've received data from server or you are ready with the datasource, call this method. Magic!
- (void) reloadCollectionView {
[self.collectionView reloadData];
// Invalidating timer for safety reasons
[timer invalidate];
// Below, for each 3.5 seconds MyViewController's 'autoScrollImageSlider' would be fired
timer = [NSTimer scheduledTimerWithTimeInterval:3.5 target:self selector:@selector(autoScrollImageSlider) userInfo:nil repeats:YES];
//This will register the timer to the main run loop
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
- (void)scrollToPreviousOrNextCell:(NSString *)direction {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
NSInteger firstIndex = 0;
NSInteger lastIndex = datasource.count - 1;
NSArray *visibleIndices = [self.collectionView indexPathsForVisibleItems];
NSInteger nextIndex = [[visibleIndices objectAtIndex:0] row] + 1;
NSInteger previousIndex = [[visibleIndices objectAtIndex:0] row] - 1;
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForRow:nextIndex inSection:0];
NSIndexPath *previousIndexPath = [NSIndexPath indexPathForRow:previousIndex inSection:0];
if ([direction isEqualToString:@"Previous"]) {
if (previousIndex < firstIndex) {
} else {
[self.collectionView scrollToItemAtIndexPath:previousIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
} else if ([direction isEqualToString:@"Next"]) {
if (nextIndex > lastIndex) {
} else {
[self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
}
});
}
-(void) autoScrollImageSlider {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
NSInteger firstIndex = 0;
NSInteger lastIndex = datasource.count - 1;
NSArray *visibleIndices = [self.collectionView indexPathsForVisibleItems];
NSInteger nextIndex = [[visibleIndices objectAtIndex:0] row] + 1;
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForRow:nextIndex inSection:0];
NSIndexPath *firstIndexPath = [NSIndexPath indexPathForRow:firstIndex inSection:0];
if (nextIndex > lastIndex) {
[self.collectionView scrollToItemAtIndexPath:firstIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
} else {
[self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}
});
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellId = @"cell";
//Use your custom cell
UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
cell.imageView.image = [datasource objectAtIndex:[indexPath row]];
return cell;
}
//Make sure you invalidate the timer here
-(void)viewWillDisappear:(BOOL)animated { [timer invalidate]; }
@接口MyViewController(){
n定时器*定时器;
NSMutableArray*数据源;
}
@属性(非原子,弱)IBUICollectionView*collectionView;
@结束
@MyViewController的实现
-(iAction)PreviousButton操作:(UIButton*)发送方{
if(数据源!=nil){
如果(datasource.count!=0){
[自我滚动到上一个或下一个单元格:@“上一个”];
}
}
}
-(iAction)下一个按钮操作:(UIButton*)发送器{
if(数据源!=nil){
如果(datasource.count!=0){
[自我滚动到上一个或下一个单元格:@“下一个”];
}
}
}
-(iAction)pauseButtonAction:(UIButton*)发送方{[timer invalidate];}
//从服务器接收数据或准备好数据源后,调用此方法。魔术
-(无效)重新加载CollectionView{
[self.collectionView-reloadData];
//出于安全原因使计时器失效
[计时器失效];
//下面,MyViewController的“autoScrollImageSlider”每3.5秒就会触发一次
计时器=[NSTimer scheduledTimerWithTimeInterval:3.5 t