I want my swift code to center a frame connected to a uipangesture to the y axis. You can see what I am looking for in the gif I created below. Right now I have figure out a way to do this. I found you can do something similar to this using nslayout constraints and making them be set to true. But it moves the box to the top of the screen and I want to do something similar to the gif below.
import UIKit
class ViewController: UIViewController {
var container = UIView()
var panGesture = UIPanGestureRecognizer()
var btn = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
[container,btn].forEach{
$0.translatesAutoresizingMaskIntoConstraints = false
view.addSubview($0)
}
container.isUserInteractionEnabled = true
btn.frame = CGRect(x: 100, y: 300, width: 100, height: 100)
container.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
container.backgroundColor = .blue
btn.backgroundColor = .red
panGesture = UIPanGestureRecognizer(target: self, action: #selector(ViewController.draggedView(_:)))
container.isUserInteractionEnabled = true
container.addGestureRecognizer(panGesture)
btn.addTarget(self, action: #selector(centerYAlighment), for: .touchDown)
}
@objc func draggedView(_ sender: UIPanGestureRecognizer) {
self.view.bringSubview(toFront: container)
let translation = sender.translation(in: self.view)
container.center = CGPoint(x: container.center.x + translation.x , y: container.center.y + translation.y)
sender.setTranslation(CGPoint.zero, in: self.view)
}
@objc func centerYAlighment(){
}
}