2015-08-21 12 views
5

Mi piacerebbe poter spostare un oggetto (nel mio caso, un'immagine "cucciolo") di 1 pixel ogni volta che si preme un pulsante. Mi sono imbattuto in vecchie soluzioni Objective-C e in codice Swift simile, ma non adatto al mio problema specifico. Mi piacerebbe conoscere un modo semplice per spostare la mia immagine. Questo è il mio codice così lontano da quello che ho potuto raccogliere (spero che sia inutilmente lungo e può essere ridotto a una riga o due):Come posso spostare un'immagine in Swift?

@IBAction func tapButton() { 
UIView.animateWithDuration(0.75, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { 
      self.puppy.alpha = 1 
      self.puppy.center.y = 0 
      }, completion: nil) 

     var toPoint: CGPoint = CGPointMake(0.0, 1.0) 
     var fromPoint : CGPoint = CGPointZero 

     var movement = CABasicAnimation(keyPath: "movement") 
     movement.additive = true 
     movement.fromValue = NSValue(CGPoint: fromPoint) 
     movement.toValue = NSValue(CGPoint: toPoint) 
     movement.duration = 0.3 

     view.layer.addAnimation(movement, forKey: "move") 
} 

risposta

5

In questo modo è possibile modificare una posizione a imageView

@IBAction func tapButton() { 
    UIView.animateWithDuration(0.75, delay: 0, options: .CurveLinear, animations: { 
     // this will change Y position of your imageView center 
     // by 1 every time you press button 
     self.puppy.center.y -= 1 
    }, completion: nil) 
} 

e rimuovere tutti gli altri codici dalla tua azione pulsante.

1

Si può fare questo.

func clickButton() { 
    UIView.animateWithDuration(animationDuration, animations: { 
     let buttonFrame = self.button.frame 
     buttonFrame.origin.y = buttonFrame.origin.y - 1.0 
     self.button.frame = buttonFrame 
    } 
} 
0
CATransaction.begin() 
CATransaction.setCompletionBlock {() -> Void in 
    self.viewBall.layer.position = self.viewBall.layer.presentationLayer().position 
} 
var animation = CABasicAnimation(keyPath: "position") 
animation.duration = ballMoveTime 

var currentPosition : CGPoint = viewBall.layer.presentationLayer().position 
animation.fromValue = NSValue(currentPosition) 
animation.toValue = NSValue(CGPoint: CGPointMake(currentPosition.x, (currentPosition.y + 1))) 
animation.removedOnCompletion = false 
animation.fillMode = kCAFillModeForwards 
viewBall.layer.addAnimation(animation, forKey: "transform") 
CATransaction.commit() 

Sostituire viewBall all'oggetto immagine

e rimuovere anche il completamento del blocco, se non si vuole.

Problemi correlati