Search code examples
iosswiftuitouch

Move Button left with finger touch and return to its first location when touch end ios Swift


i am new to Swift and working an application in which i move my green Button(show in picture) move with finger to left side and when finger is removed from the button then button moves to its previous position. Also there are four different button background images that change after every movement of button from current position to left side. But i am unable to understand that how i do this. please help me to do my task.

enter image description here

Here is my code

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {


    location = ((touches.first)?.location(in: self.view))!

    let position = view.convert(location, to: view)

    print("Touches Began \(location)")
    }

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    location = ((touches.first)?.location(in: self.view))!

    let position = view.convert(location, to: view)

    print("touches Moved: \(location)")
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    // dont know how i perform

}

Solution

  •     @IBOutlet weak var yourButtonOutlet: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        yourButtonOutlet.addTarget(self, action: #selector(t1),for: .touchUpInside)
        yourButtonOutlet.addTarget(self, action: #selector(t2),for: .touchDown)
    
    
    
        // Do any additional setup after loading the view.
    }
    func t1() {
        print("touch end")
        yourButtonOutlet.frame = CGRect(x: yourButtonOutlet.frame.origin.x + 50, y: yourButtonOutlet.frame.origin.y, width: yourButtonOutlet.frame.size.width, height: yourButtonOutlet.frame.size.height)
    
    }
    func t2() {
        print("touch Start")
        yourButtonOutlet.frame = CGRect(x: yourButtonOutlet.frame.origin.x - 50, y: yourButtonOutlet.frame.origin.y, width: yourButtonOutlet.frame.size.width, height: yourButtonOutlet.frame.size.height)
    
    }
    

    // and for change image on click button

    var selected  = true
    @IBAction func btnUserAction(_ sender: UIButton) {
        if selected  == true {
            sender.setImage(UIImage.init(named: "tick"), for: .normal)
            selected = false;
        }
        else{
            sender.setImage(UIImage.init(named: "unTick"), for: .normal)
            selected = true;
        }
    }