Thursday, February 21, 2019

Move a view Swift

We want a view like button move down 100dp, use this in viewDidLoad.
UIView.animateWithDuration(0.4, animations: {
self.button.center.y += 100
 })
To make it move across screen, use
self.button.center.x += 100
To make it diagonal move, use both of them.
To make it move forward and back.
let op = UIViewAnimationOptions.Repeat
let rig = self.button.center.x
UIView.animateWithDuration(1, delay: 0, options: op, animations: {
self.button.center.x += 100
            }, completion: {
_in
self.button.center.x = rig
        })
To make it jump to another position at 100dp distance, use
let op = UIViewAnimationOptions.Repeat
UIView.animateWithDuration(0.8, delay: 0,
                                   usingSpringWithDamping: 0.7,
                                   initialSpringVelocity: 20,
                                   options: op,
                                   animations: {
self.button.center.x += 100
            }, completion: nil)
To make it move along with user finger when they touch on it, create a function.
func hand(sender: UIPanGestureRecognizer){
if sender.state != .Ended&& sender.state != .Failed{
let location = sender.locationInView(sender.view!.superview!)
            sender.view!.center = location
        }
    }
Add these lines in viewDidLoad.
let t = UIPanGestureRecognizer(target:self, action:#selector(ViewController.hand(_:)))

button.addGestureRecognizer(t)


No comments:

Post a Comment