Reputation:
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
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:
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