2017-07-06 41 views
2

我已經將UIDynamics添加到imageview併爲此使用了平移手勢。它與平移手勢正常工作,但是當我應用捏手勢,它不工作。它顯示大的圖像查看,但是當我開始拖動時,它會更改爲原始大小。UIKit動態與平移,旋轉和捏手勢

這裏是我的代碼:

func handleAttachmentGesture(_ sender: UIPanGestureRecognizer) { 
    let location = sender.location(in: emojiSuperView!) 
    let boxLocation = sender.location(in: self) 
    switch sender.state { 
    case .began: 
     print("Your touch start position is \(location)") 
     print("Start location in image is \(boxLocation)") 

     animator.removeAllBehaviors() 

     let centerOffset = UIOffset(horizontal: boxLocation.x - self.bounds.midX, vertical: boxLocation.y - self.bounds.midY) 
     attachmentBehavior = UIAttachmentBehavior(item: self, offsetFromCenter: centerOffset, attachedToAnchor: location) 
     animator.addBehavior(attachmentBehavior) 
    case .ended: 
     print("Your touch end position is \(location)") 
     print("End location in image is \(boxLocation)") 

     animator.removeAllBehaviors() 

     // 1 
     let velocity = sender.velocity(in: emojiSuperView!) 
     let magnitude = sqrt((velocity.x * velocity.x) + (velocity.y * velocity.y)) 

     if magnitude > ThrowingThreshold { 
      // 2 
      let pushBehavior = UIPushBehavior(items: [self], mode: .instantaneous) 
      pushBehavior.pushDirection = CGVector(dx: velocity.x/10, dy: velocity.y/10) 
      pushBehavior.magnitude = magnitude/ThrowingVelocityPadding 

      self.pushBehavior = pushBehavior 
      animator.addBehavior(pushBehavior) 

      // 3 
      let angle = Int(arc4random_uniform(20)) - 10 

      itemBehavior = UIDynamicItemBehavior(items: [self]) 
      itemBehavior.friction = 0.2 
      itemBehavior.allowsRotation = true 
      itemBehavior.addAngularVelocity(CGFloat(angle), for: self) 
      animator.addBehavior(itemBehavior) 
     } 
    default: 
     attachmentBehavior.anchorPoint = sender.location(in: emojiSuperView!) 
     break 
    } 
} 


func recognizePinchGesture(sender: UIPinchGestureRecognizer) 
{ 
    weak var dynamicItem: UIDynamicItem? 
    // whatever your item is, probably a UIView 
    dynamicItem = self 
    let behavior = UIGravityBehavior(items: [dynamicItem!]) 
    let animator = UIDynamicAnimator(referenceView: emojiSuperView!) 
    // or however you're getting your animator 
    animator.addBehavior(behavior) 
    sender.view!.transform = sender.view!.transform.scaledBy(x: sender.scale, y: sender.scale) 
    animator.updateItem(usingCurrentState: self) 
    self.animator.updateItem(usingCurrentState: self) 
    sender.scale = 1 
} 
+0

好問題+1,我也面臨同樣的問題, – Dhiru

回答

0

當使用者做任何改變事件,保存當前變換到一個全局變量。

之後,當平移開始使用UIAttachmentBehavior的動作屬性分配開始狀態的新變換。

 attachmentBehavior.action = { 
      self.attachmentBehavior.items[0].transform = self.aTransform 
     }