I added the constraint to the buttons created in my UIView
func CreateButtonWithIndex(index:Int) {
newButton.setTranslatesAutoresizingMaskI
Looks like you are just adding more and more constraint. You can't do that because they obviously conflict with each other. You are basically saying "put the view at position x = 1, x = 2, x = 3, x = 4 and x = 5".
You have to remove the old constraints. You have two options to do that.
Save the constraints in an array, and remove these constraints from the view before adding new ones.
Or you keep a reference to the constraints that change and adjust their properties.
Since your constraints just differ in the constant value you should go for option 2.
Make newButtonConstraintX
and newButtonConstraintY
a variable of the viewController.
e.g.
class ViewController: UIViewController {
var newButtonConstraintX: NSLayoutConstraint!
var newButtonConstraintY: NSLayoutConstraint!
func CreateButtonWithIndex(index:Int) {
newButtonConstraintX = NSLayoutConstraint(item: newButton, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: CGFloat(riga))
newButtonConstraintY = NSLayoutConstraint(item: newButton, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: CGFloat(colonna))
/* ... */
}
func pan(rec:UIPanGestureRecognizer) {
/* ... */
newButtonConstraintX.constant = line
newButtonConstraintY.constant = column
button.layoutIfNeeded()
}