2015-08-21 9 views
5

Ich möchte in der Lage sein, ein Objekt (in meinem Fall ein Bild "Welpe") jedes Mal um 1 Pixel zu bewegen, wenn eine Taste gedrückt wird. Ich bin auf alte Objective-C-Lösungen sowie Swift-Code gestoßen, der ähnlich war, aber keinen, der zu meinem spezifischen Problem passte. Ich würde gerne eine einfache Möglichkeit kennen, mein Bild zu bewegen. Dies ist mein Code so weit von dem, was ich sammeln konnte (ich hoffe, dass es unnötig lang ist und kann auf eine Linie oder zwei reduziert werden):Wie kann ich ein Bild in Swift verschieben?

@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") 
} 

Antwort

5

Auf diese Weise können Sie Ihre eine Position imageView ändern

@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) 
} 

und alle anderen Code aus Ihrer Schaltfläche Aktion entfernen.

1

Sie dies tun können.

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() 

viewBall Objekt zu Ihrem Bild ersetzen

Und auch Abschluss Block entfernen, wenn Sie nicht wollen.

Verwandte Themen