Swift版PhotoStackView——照片叠放视图

前端之家收集整理的这篇文章主要介绍了Swift版PhotoStackView——照片叠放视图前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

前言

之前流行过一种图片展示视图——photo stack,即照片叠放视图。大致上是这个样子的:

图片出自code4app)
现在我们已经能够使用UICollectionViewLayout来实现这种视图了。Apple给的示例代码中就有这样一个layout,并且示例代码中不仅仅是展示这样的视图,还有非常棒的layout过度动画(结合手势)。在这之前,也有非常多的开源代码能实现这样的效果本文正是借鉴了开源的源代码“PhotoStackView”,使用Objective-C实现,并且带手势移动图片功能。由于这是上一学期课设的时候拿来用的库,结果现在找不到了,无法给出链接,还望见谅。

最后的效果图如下

这样重复造轮子的目的是什么呢?一方面,不使用UICollectionViewLayout而是纯粹的用UIView来实现,提高灵活性,方便“私人订制”。另一方面,学习大神的源代码,从中学习一下自定义库的书写方式等。最后,swift。。天杀的swift,是谁说swift对新手友好来着
当然,这里也不是简单的对源代码的搬运、抄袭与翻译,我还根据自己的需要给他改了一个bug,添加了一些功能,比如全屏展示与返回等。示例图如下:

  • 全屏展示

图片有些卡,测试运行时还是非常流畅的)

思路

  • 使用若干和自己一样大的view来装载图片,每次添加图片到视图上时为其随机旋转一定角度,把最前面的这张旋转角度设为0。
  • “view装载图片”的意思是,view里面放一个imageView,为什么不直接用imageVIew呢?因为我们要放边框,边框可以是图片,另外在highlighted状态下也可以用图片自定义颜色铺在图片上,因此使用一个view统一管理
  • 添加pan手势,当手指移动时让view跟着做相应平移,手指松开时根据velocity决定返回还是移到最后
  • 综上,我们还需要不少辅助方法,例如获取顶部图片和其下标、使用动画移动view、让view旋转到某一度数等

代码

computed property & stored property

oc中可以声明属性然后覆写setter或getter,从而实现赋值或取值时进行一些操作的功能,如下代码

  1. @property(strong,nonatomic) NSString *someString
  2.  
  3. - (void)setSomeString() {...}
  4. - (NSString *)someString() {...}

swift中相对应的写法,目前我知道的有两种,一种是使用computed property 的set和get,缺点是必须同时声明一个stored property(?可以不用吗,求科普),很像oc2.0之前的属性。另一种是使用监听器(didSet和willSet),缺点是只能对setter操作,不能对getter操作。
但是,要想实现重写父类的setSomeThing这样的功能,只能通过监听器的方法。否则会报错

由上,该类用到的属性如下(部分):

  1. //MARK: computed property
  2.  
  3. var s_rotationOffset: CGFloat = 0.0
  4. /// the scope of offset of rotation on every photo except the first one. default is 4.0.
  5. /// ie,4.0 means rotate iamge with degree between (-4.0,4.0)
  6. var rotationOffset: CGFloat {
  7. set {
  8. if s_rotationOffset == newValue {
  9. return
  10. }
  11.  
  12. s_rotationOffset = newValue
  13. reloadData()
  14. }
  15. get {
  16. return s_rotationOffset
  17. }
  18. }
  19.  
  20. var s_photoImages: [UIView]?
  21. var photoImages: [UIView]? {
  22. set {
  23. //remove all subview and prepare to re-add all images from data source
  24. for view in subviews {
  25. view.removeFromSuperview()
  26. }
  27.  
  28. if let images = newValue {
  29. for view in images {
  30. //keep the original transfrom for the existing images
  31. if let index = find(images,view),count = s_photoImages?.count where index < count {
  32. let existingView = s_photoImages![index]
  33. view.transform = existingView.transform
  34. } else {
  35. makeCrooked(view,animated: false)
  36. }
  37.  
  38. insertSubview(view,atIndex: 0)
  39. }
  40. }
  41.  
  42. s_photoImages = newValue
  43. }
  44. get {
  45. return s_photoImages
  46. }
  47. }
  48.  
  49. override var highlighted: Bool {
  50. didSet {
  51. let photo = self.topPhoto()?.subviews.last as! UIImageView
  52. if highlighted {
  53. let view = UIView(frame: self.bounds)
  54. view.backgroundColor = self.highlightColor
  55. photo.addSubview(view)
  56. photo.bringSubviewToFront(view)
  57. } else {
  58. photo.subviews.last?.removeFromSuperview()
  59. }
  60. }
  61. }
  62.  
  63. override var frame: CGRect {
  64. didSet {
  65. if CGRectEqualToRect(oldValue,self.frame) {
  66. return
  67. }
  68.  
  69. reloadData()
  70. }
  71. }

上面大部分还有其他省略的大都是一样的思路:设置新值时调用reloadData刷新,主要是上面那个photoImage数组的setter:首先移除当前所有的子视图,接下来遍历新数组,那句判断if let index = find(images,count = s_photoImages?.count where index < count的作用是判断此次循环中view是否是之前已经添加到界面上的,如果是,则保留其transform不变,否则为其重新生产一个旋转角度(产生照片堆效果),这样做保证了添加照片时原先的照片形状不会变。

Set up & Touches

初始化的工作非常简单,一方面为属性设置默认值,另一方面添加手势监听。

  1. //MARK: Set up
  2.  
  3. override init(frame: CGRect) {
  4. super.init(frame: frame)
  5. setup()
  6. }
  7.  
  8. required init(coder aDecoder: NSCoder) {
  9. super.init(coder: aDecoder)
  10. setup()
  11. }
  12.  
  13. func setup() {
  14. //default value
  15. borderWidth = 5.0
  16. showBorder = true
  17. rotationOffset = 4.0
  18.  
  19. let panGR = UIPanGestureRecognizer(target: self,action: Selector("handlePan:"))
  20. addGestureRecognizer(panGR)
  21.  
  22. let tapGR = UITapGestureRecognizer(target: self,action: Selector("handleTap:"))
  23. addGestureRecognizer(tapGR)
  24.  
  25. reloadData()
  26. }
  27.  
  28. override func sendActionsForControlEvents(controlEvents: UIControlEvents) {
  29. super.sendActionsForControlEvents(controlEvents)
  30. highlighted = (controlEvents == .TouchDown)
  31. }

sendActionsForControlEvents自定义UIControl时可能会使用或重写的方法,作用是发送事件。为了说明这一点,这里顺带附上view的触摸方法

  1. //MARK: Touch Methods
  2.  
  3. override func touchesBegan(touches: Set<NSObject>,withEvent event: UIEvent) {
  4. super.touchesBegan(touches,withEvent: event)
  5.  
  6. sendActionsForControlEvents(.TouchDown)
  7. }
  8.  
  9. override func touchesMoved(touches: Set<NSObject>,withEvent event: UIEvent) {
  10. super.touchesMoved(touches,withEvent: event)
  11.  
  12. sendActionsForControlEvents(.TouchDragInside)
  13. }
  14.  
  15. override func touchesEnded(touches: Set<NSObject>,withEvent event: UIEvent) {
  16. super.touchesEnded(touches,withEvent: event)
  17.  
  18. sendActionsForControlEvents(.TouchCancel)
  19. }

例如,当用户点击该控件时,发送UIControlEventTouchDown事件,这样使用该控件的人就可以通过addTarget:selector:forControlEvent:方法对此事件添加监听了。我们平时最经常使用的button不就是对TouchUpInside事件进行监听的吗。

reloadData

刷新视图时,要做的事情有:重新获取size,计算frame,添加border,设置images

  1. /** use this method to reload photo stack view when data has changed */
  2. func reloadData() {
  3. if dataSource == nil {
  4. photoImages = nil
  5. return
  6. }
  7.  
  8. if let number = dataSource?.numberOfPhotosInStackView(self) {
  9. var images = [UIView]()
  10. let border = borderImage?.resizableImageWithCapInsets(UIEdgeInsets(top: borderWidth,left: borderWidth,bottom: borderWidth,right: borderWidth))
  11. let topIndex = indexOfTopPhoto()
  12.  
  13. for i in 0..<number {
  14. if let image = dataSource?.stackView(self,imageAtIndex: i) {
  15.  
  16. //add image view for every image
  17. let imageView = UIImageView(image: image)
  18. var viewFrame = CGRectMake(0,0,image.size.width,image.size.height)
  19.  
  20. if let ds = dataSource where ds.respondsToSelector(Selector("stackView:sizeOfPhotoAtIndex:")) {
  21. let size = ds.stackView!(self,sizeOfPhotoAtIndex: i)
  22. viewFrame.size = size
  23. }
  24.  
  25. imageView.frame = viewFrame
  26.  
  27. let view = UIView(frame: viewFrame)
  28.  
  29. //add border for view
  30. if showBorder {
  31. if let b = border {
  32. viewFrame.origin = CGPoint(x: borderWidth,y: borderWidth)
  33. imageView.frame = viewFrame
  34. view.frame = CGRect(x: 0,y: 0,width: imageView.frame.width + 2 * borderWidth,height: imageView.frame.height + 2 * borderWidth)
  35.  
  36. let backgroundImage = UIImageView(image: b)
  37. backgroundImage.frame = view.frame
  38. view.addSubview(backgroundImage)
  39. } else {
  40. view.layer.borderWidth = borderWidth
  41. view.layer.borderColor = UIColor.whiteColor().CGColor
  42. }
  43.  
  44. }
  45. view.addSubview(imageView)
  46.  
  47. //add view to array
  48. images.append(view)
  49. view.tag = i
  50. view.center = CGPoint(x: CGRectGetMidX(bounds),y: CGRectGetMidY(bounds))
  51. }
  52. }
  53.  
  54. photoImages = images
  55. goToImageAtIndex(topIndex)
  56. }
  57.  
  58. }

这里要干的仅有前三件事,添加photos的任务交给photoImages的setter去做,这个之前已经说过了。

逻辑相关

在谈这个之前,让我们先来了解一下view的组织方式。如果一个view内有若干个subview,你知道subviews.lastObject和subviews.firstObject分别指哪个吗?
事实上,越是靠近我们的,下标识越小。换句话说,subviews[0]指的是子视图中位于最底层的,被其他子视图遮住了的那一个,而subviews.lastObject指的则是最顶层的,能被我们看到(一般来说)的。
这样,很容易能得出下面几个函数

  1. /** find the index of top photo :returns: index of top photo */
  2. func indexOfTopPhoto() -> Int {
  3. if let images = photoImages,let photo = topPhoto() {
  4. if let index = find(images,photo) {
  5. return index
  6. }
  7. }
  8. return 0
  9. }
  10.  
  11. /** get the top photo on photo stack :returns: current first photo */
  12. func topPhoto() -> UIView? {
  13. if subviews.count == 0 {
  14. return nil
  15. }
  16. return subviews[subviews.count - 1] as? UIView
  17. }
  18.  
  19. /** jump to photo at index */
  20. func goToImageAtIndex(index: Int) {
  21. if let photos = photoImages {
  22. for view in photos {
  23. if let idx = find(photos,view) where idx < index {
  24. sendSubviewToBack(view)
  25. }
  26. }
  27. }
  28. makeStraight(topPhoto()!,animated: false)
  29. }

swift知识补充:swift中没有indexForObject:这样的方法,众所周知,swift更多的是“函数式编程”,因此Int、Float甚至Array、Dictionary都是结构体(虽然和类挺相似),我们也是使用一些函数来对这些结构体操作。例如这里取代上述方法的是find()函数

有了这些方法,我们就能使用动画后处理view的层级关系了。

动画相关

这里用到的动画相关的都非常简单,所以直接上代码

  1. //MARK: Animations
  2.  
  3. func returnToCenter(view: UIView) {
  4. UIView.animateWithDuration(0.2,animations: { () -> Void in view.center = CGPoint(x: CGRectGetMidX(self.bounds),y: CGRectGetMidY(self.bounds)) }) } func flickAway(view: UIView,withVelocity velocity: CGPoint) { if let del = delegate where del.respondsToSelector(Selector("stackView:willFlickAwayPhotoFromIndex:toIndex:")) { let from = indexOfTopPhoto() var to = from + 1 if let number = dataSource?.numberOfPhotosInStackView(self) where to >= number { to = 0 } del.stackView!(self,willFlickAwayPhotoFromIndex: from,toIndex: to) } let width = CGRectGetWidth(bounds) let height = CGRectGetHeight(bounds) var xPosition: CGFloat = CGRectGetMidX(bounds) var yPosition: CGFloat = CGRectGetMidY(bounds) if velocity.x > 0 { xPosition = CGRectGetMidX(bounds) + width } else if velocity.x < 0 { xPosition = CGRectGetMidX(bounds) - width } if velocity.y > 0 { yPosition = CGRectGetMidY(bounds) + height } else if velocity.y < 0 { yPosition = CGRectGetMidY(bounds) - height } UIView.animateWithDuration(0.1,animations: { () -> Void in view.center = CGPoint(x: xPosition,y: yPosition) }) { (finished) -> Void in
  5. self.makeCrooked(view,animated: true)
  6. self.sendSubviewToBack(view)
  7. self.makeStraight(self.topPhoto()!,animated: true)
  8. self .returnToCenter(view)
  9.  
  10. if let del = self.delegate where del.respondsToSelector("stackView:didRevealPhotoAtIndex:") {
  11. del.stackView!(self,didRevealPhotoAtIndex:self.indexOfTopPhoto())
  12. }
  13. }
  14. }
  15.  
  16. func rotate(degree: Int,onView view: UIView,animated: Bool) {
  17. let radian = CGFloat(degree) * CGFloat(M_PI) / 180
  18.  
  19. if animated {
  20. UIView.animateWithDuration(0.2,animations: { () -> Void in view.transform = CGAffineTransformMakeRotation(radian) }) } else { view.transform = CGAffineTransformMakeRotation(radian) } } func makeCrooked(view: UIView,animated: Bool) { let min = Int(-rotationOffset) let max = Int(rotationOffset) let scope = UInt32(max - min - 1) let randomDegree = Int(arc4random_uniform(scope)) let degree: Int = min + randomDegree rotate(degree,onView: view,animated: animated) } func makeStraight(view: UIView,animated: Bool) { rotate(0,animated: animated) }

swift相关:一直不是太明白swift中可选值的意义是什么。到是给我们带来了不少麻烦,因为不怎么想全都用强解(!),所以用了大量if let解包的方式。其中oc中很简单就能完成的操作:

  1. if (self.delegate responseToSelector:@selector(@"someMethod")) {
  2. [self.delegate someMethod];
  3. }

到了swift中

  1. if let del = delegate where del.responseToSelector(Selector("someMethod") {
  2. del.someMethod()
  3. }

且不说swift的Selector机制,每次都这样写可真是要累死人了:[

手势

和之前说的一样,pan手势中要做的就是通知代理,让view随手指移动,释放手指后根据velocity将view归位或切换到最后一张。

  1. //MARK: Gesture Recognizer
  2.  
  3. func handlePan(recognizer: UIPanGestureRecognizer) {
  4. if let topPhoto = self.topPhoto() {
  5. let velocity = recognizer.velocityInView(recognizer.view)
  6. let translation = recognizer.translationInView(recognizer.view!)
  7.  
  8. if recognizer.state == .Began {
  9. sendActionsForControlEvents(.TouchCancel)
  10.  
  11. if let del = delegate where del.respondsToSelector(Selector("stackView:willBeginDraggingPhotoAtIndex")) {
  12. del.stackView!(self,willBeginDraggingPhotoAtIndex: self.indexOfTopPhoto())
  13. }
  14. } else if recognizer.state == .Changed {
  15. topPhoto.center = CGPoint(x: topPhoto.center.x + translation.x,y: topPhoto.center.y + translation.y)
  16. recognizer.setTranslation(CGPoint.zeroPoint,inView: recognizer.view)
  17. } else if recognizer.state == .Ended || recognizer.state == .Cancelled {
  18. if abs(velocity.x) > 200 {
  19. flickAway(topPhoto,withVelocity: velocity)
  20. } else {
  21. returnToCenter(topPhoto)
  22. }
  23. }
  24.  
  25. }
  26.  
  27. }
  28.  
  29. func handleTap(recognizer: UIGestureRecognizer) {
  30. sendActionsForControlEvents(.TouchUpInside)
  31.  
  32. if let del = delegate where del.respondsToSelector(Selector("stackView:didSelectPhotoAtIndex:")) {
  33. del.stackView!(self,didSelectPhotoAtIndex: self.indexOfTopPhoto())
  34. }
  35. }

Show All Images

创建一层黑色的遮罩(view),然后将每个view从自己原来的位置移到计算好的新位置,为了产生顺序关系,为每个view 的动画设置各自的delay。点击黑色遮罩后所有view回位,view消失。

  1. func showAllPhotos() {
  2. let screenBounds = UIScreen.mainScreen().bounds
  3. let maskView = UIView(frame: screenBounds)
  4. maskView.backgroundColor = UIColor.blackColor()
  5. maskView.alpha = 0
  6. UIApplication.sharedApplication().keyWindow?.addSubview(maskView)
  7.  
  8. UIView.animateWithDuration(0.1,delay: 0.0,options: nil,animations: { () -> Void in maskView.alpha = 1.0 }) { (_) -> Void in
  9.  
  10. }
  11.  
  12.  
  13. let column = 3
  14. let imageWidth = 80
  15. let padding = (Int(screenBounds.width) - column * imageWidth) / (column + 1)
  16.  
  17. if let photos = photoImages {
  18. for view in photos {
  19.  
  20. //set the initial location
  21. view.removeFromSuperview()
  22. maskView.addSubview(view)
  23. view.frame = frame
  24.  
  25. if let index = find(photos,view) {
  26. UIView.animateWithDuration(0.1,delay: NSTimeInterval(Double(index) * 0.1),animations: { () -> Void in view.frame = CGRect(x: padding + (index % column) * (imageWidth + padding),y: padding + (index / column) * (padding + imageWidth),width: imageWidth,height: imageWidth) },completion: { (finished) -> Void in }) } } } let tapGR = UITapGestureRecognizer(target: self,action: Selector("removeMaskView:")) maskView.addGestureRecognizer(tapGR) }
  1. func removeMaskView(recognizer: UITapGestureRecognizer) {
  2. let maskView = recognizer.view!
  3. for i in stride(from: maskView.subviews.count - 1,through: 0,by: -1) {
  4. let photo = maskView.subviews[i] as? UIView
  5. UIView.animateWithDuration(0.25,animations: { () -> Void in photo?.frame = self.frame },completion: { (_) -> Void in }) } UIView.animateWithDuration(0.25,animations: { () -> Void in maskView.alpha = 0.0 }) { (_) -> Void in
  6. maskView.removeFromSuperview()
  7. self.reloadData()
  8. }
  9. }

代码

本文的源代码可以从这里下载

总结

刚接触swift不久就直接写东西,确实不好写,swift为了安全做了很多努力,但却增加了一些注意事项。一个Int乘以一个Double都报错的“强类型“检查实在不习惯。但是不得不说这门语言确实有意思,省略小括号,不用分号,switch,where…以后多接触,说不定就能喜欢上这门语言了:]

猜你在找的Swift相关文章