I added the constraint to the buttons created in my UIView
func CreateButtonWithIndex(index:Int) {
newButton.setTranslatesAutoresizingMaskI
Update Rob's Answer to Swift 3:
class ViewController: UIViewController {
private var xConstraint: NSLayoutConstraint!
private var yConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel()
label.text = "x"
label.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(label)
// I don't really need to save references to these, so these are local variables
let widthConstraint = NSLayoutConstraint(item: drugToDrugView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50)
let heightConstraint = NSLayoutConstraint(item: drugToDrugView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50)
// but since I'll be modifying these later, these are class properties
xConstraint = NSLayoutConstraint(item: drugToDrugView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0)
yConstraint = NSLayoutConstraint(item: drugToDrugView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0)
drugToDrugView.addConstraints([widthConstraint, heightConstraint, xConstraint, yConstraint])
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
view.addGestureRecognizer(pan)
}
private var originalCenter: CGPoint!
func handlePan(gesture: UIPanGestureRecognizer) {
if gesture.state == .began {
originalCenter = CGPoint(x: xConstraint.constant, y: yConstraint.constant)
}
let translation = gesture.translation(in: gesture.view!)
xConstraint.constant = originalCenter.x + translation.x
yConstraint.constant = originalCenter.y + translation.y
view.setNeedsLayout()
}