2016-09-26 47 views
1

我有一个collectionView,用于显示我的入职屏幕。每个单元格都占用视图的全部宽度和高度,目前我可以在每个单元格(页面)之间进行细滑动。按钮点击(swift)移动集合视图

我必须实现下一个按钮。此按钮只会在每次点击时将collectionView移动到1个索引上(直到结束)。我只是试图让它立即行动,即使有几个类似的问题,我迄今还没有能够提出解决方案。

这是我曾尝试

@IBAction func nextPageButtonClicked(_ sender: AnyObject) { 
     let visibleItems: NSArray = self.collectionView.indexPathsForVisibleItems as NSArray 
     let currentItem: NSIndexPath = visibleItems.object(at: 0) as! NSIndexPath 
     let nextItem: NSIndexPath = NSIndexPath(row: currentItem + 1, section: 0) 
     self.collectionView.scrollToItem(at: nextItem as IndexPath, at: .left, animated: true) 
    } 

我得到一个错误约第4行执行的二进制运算符(CURRENTITEM + 1),但即使我硬编码的数量,并尝试运行它,我还是不要让滚动功能​​

回答

7

您试图增加indexPath,您必须增加indexPath的行。

let nextItem = NSIndexPath(row: currentItem.row + 1, section: 0) 

@IBAction func nextPageButtonClicked(_ sender: AnyObject) { 

    guard let indexPath = collectionView.indexPathsForVisibleItems.first.flatMap({ 
     IndexPath(item: $0.row + 1, section: $0.section) 
    }), collectionView.cellForItem(at: indexPath) != nil else { 
     return 
    } 

    collectionView.scrollToItem(at: indexPath, at: .left, animated: true) 
} 
+1

传说!谢了哥们! – user934902

+0

它没有工作还需要点击多次移动 – wod

0
@IBAction func showNextItemCollectionViewOnClick(_ sender: Any) { 

     let visibleItems: NSArray = self.collectionView.indexPathsForVisibleItems as NSArray 

     var minItem: NSIndexPath = visibleItems.object(at: 0) as! NSIndexPath 
     for itr in visibleItems { 

      if minItem.row > (itr as AnyObject).row { 
       minItem = itr as! NSIndexPath 
      } 
     } 

     let nextItem = NSIndexPath(row: minItem.row + 1, section: 0) 
     self.collectionView.scrollToItem(at: nextItem as IndexPath, at: .left, animated: true) 
    } 

步骤:

  1. 查找 “visibleItems” 所有可见项可变
  2. 查找分钟项存在于可见的项目
  3. 转到下一个项目
  4. 滚动到所需的项目。

注:本作品,即使在情况下,当一个以上的项目出现在按钮集合视图&点击我们想要的“一个”多项目是可见的,如果我们想要一个以上的项目变更为“1”的运动达到所需的价值。

0

尝试这些方法离开以及您的收藏细胞

权增量右增量

@IBAction func Btn_RightAction(_ sender: Any) 
{ 
    let visibleItems: NSArray = self.collectionView.indexPathsForVisibleItems as NSArray 
    let currentItem: IndexPath = visibleItems.object(at: 0) as! IndexPath 
    let nextItem: IndexPath = IndexPath(item: currentItem.item + 1, section: 0) 
      if nextItem.row < ImgArr.count { 
     self.collectionView.scrollToItem(at: nextItem, at: .left, animated: true) 

    } 
} 

左增量

@IBAction func Btn_LeftAction(_ sender: Any) 
{ 
    let visibleItems: NSArray = self.collectionView.indexPathsForVisibleItems as NSArray 
    let currentItem: IndexPath = visibleItems.object(at: 0) as! IndexPath 
    let nextItem: IndexPath = IndexPath(item: currentItem.item - 1, section: 0) 
    if nextItem.row < ImgArr.count && nextItem.row >= 0{ 
     self.collectionView.scrollToItem(at: nextItem, at: .right, animated: true) 

    } 
}