user6012622
user6012622

Reputation:

Swift 3 - CGAffineTransform does not work

I'm creating a button programmatically and CGAffineTransform does not work in my project when adding in addTarget, why?

EDIT :

func createButtonPuzzle(id: Int) {

     for i in 1...14 {

            let btnButton = UIButton(type: .roundedRect)
            btnButton.frame = CGRect(x: self.view.frame.size.width / 2, y: self.view.frame.size.height / 2, width: 100, height: 100)
            btnButton.backgroundColor = .blue
            btnButton.setTitle("iButton", for: .normal)
            btnButton.addTarget(self, action: #selector(moveButton(sender:)), for: .touchUpInside)

            view.addSubview(btnButton)   
     }
}


func moveButton(sender: UIButton) {

    if sender.tag == 1 {

        if sender.transform == CGAffineTransform.identity {

            UIView.animate(withDuration: 0.5, animations: 
            sender.transform = CGAffineTransform(translationX: 50, y: 100)

            })
        }                
    }
}

Upvotes: 2

Views: 2579

Answers (1)

unkgd
unkgd

Reputation: 671

In the function, instead of using sender.transform, use btnButton.transform, this is caused because you are out of scope, and sender might be dismissed, which causes the animation to dismiss.

Another option is to strongly hold the object:

let tappedButton : UIButton = sender

and then use tappedButton

EDIT

I mean something like this:

func moveButton(sender: UIButton) {

    if ((sender.tag == 1) && (sender == self.btnButton)) {

        if self.btnButton.transform == CGAffineTransform.identity {

            UIView.animate(withDuration: 0.5, animations: 
                self.btnButton.transform = CGAffineTransform(translationX: 50, y: 100)

            })
        }                
    }
}

EDIT - 2

According to your code there are 2 problems:

  1. All 14 buttons are stacked 1 on top of the other, meaning button 14 will be the topmost button instead of button 1.
  2. You are not setting the tag, and then it fails in your check in moveButton:

    func createButtonPuzzle(id: Int) {

     for i in 1...14 {
    
            let btnButton = UIButton(type: .roundedRect)
            btnButton.frame = CGRect(x: self.view.frame.size.width / 2, y: self.view.frame.size.height / 2, width: 100, height: 100)
            btnButton.backgroundColor = .blue
            btnButton.setTitle("iButton", for: .normal)
            btnButton.addTarget(self, action: #selector(moveButton(sender:)), for: .touchUpInside)
    
            **btnButton.tag = i // This is missing **
    
            view.addSubview(btnButton)   
     }
    

    }

And then this fails: if sender.tag == 1 {

So to test it and see it working, first you need to either go from 14 to 1 and just from 1..<2 or reposition the buttons in different positions so that it will actually work.

Then the tags will be set and when button with tag 1 will be tapped it will work

Upvotes: 2

Related Questions