A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© xqlyn123 中级黑马   /  2015-12-1 21:51  /  812 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

我是UICollectionView的忠实粉丝。这个类比起它的老哥UITableView类具有更高的可定制性。现在我用collection view的次数要比用table view还多。随着iOS9的到来,它支持简单的重排。在此之前,重排不可能有现成的方法,同时这样做也是件痛苦的工作。现在让我们来看看API,你可以在GitHub找到相应的Xcode工程
添加简单重排的最简单的方式是用UICollectionViewController。它现在有了一个新的属性叫installsStandardGestureForInteractiveMovement(为交互式移动工作设置标准手势),这个属性的添加使得我们可以用标准手势来对cell单元进行重新排序。该属性默认值为true,这意味着我们只需要重载一个方法就可以让它正常工作。

override func collectionView(collectionView: UICollectionView,    moveItemAtIndexPath sourceIndexPath: NSIndexPath,    toIndexPath destinationIndexPath: NSIndexPath) {    // move your data order}Collection view推断每个item(元素)可以被移动,因为moveItemAtIndexPath函数被重载了。
当我们想使用一个带有collection view的简单的UIViewController时,事情变得更加复杂。我们还需要实现之前提到的UICollectionViewDataSource的方法,但我们需要重写installsStandardGestureForInteractiveMovement。别担心,这些也很容易被支持。UILongPressGestureRecognizer是一个持续的、完全支持平移的手势识别器。

override func viewDidLoad() {    super.viewDidLoad()                longPressGesture = UILongPressGestureRecognizer(target: self, action: "handleLongGesture:")        self.collectionView.addGestureRecognizer(longPressGesture)}    func handleLongGesture(gesture: UILongPressGestureRecognizer) {        switch(gesture.state) {        case UIGestureRecognizerState.Began:            guard let selectedIndexPath = self.collectionView.indexPathForItemAtPoint(gesture.locationInView(self.collectionView)) else {                break            }            collectionView.beginInteractiveMovementForItemAtIndexPath(selectedIndexPath)        case UIGestureRecognizerState.Changed:            collectionView.updateInteractiveMovementTargetPosition(gesture.locationInView(gesture.view!))        case UIGestureRecognizerState.Ended:            collectionView.endInteractiveMovement()        default:            collectionView.cancelInteractiveMovement()        }    }我们储存了被选择的索引路径,这个路径从longPressGesture handler(长按手势处理器)中获得,这个路径还取决于它是否有任何我们允许的,跟平移手势相关的值。接下来我们根据手势状态调用一些新的collection view方法:
  • beginInteractiveMovementForItemAtIndexPath(indexPath: NSIndexPath)?开始在特定的索引路径上对cell(单元)进行Interactive Movement(交互式移动工作)。
  • updateInteractiveMovementTargetPosition(targetPosition: CGPoint)?在手势作用期间更新交互移动的目标位置。】
  • endInteractiveMovement()?在完成手势动作后,结束交互式移动
  • cancelInteractiveMovement()?取消Interactive Movement。

这让处理平移手势更容易理解了。

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马