NA000022 NA000022 - 5 months ago 23x
Swift Question

Selector method of UIButton not called during animation

enter image description hereI have dynamically created buttons on a dynamic view and later I add that dynamic view to main view.

Everything is working well except that the selector method of UIButton is not called.

var baseView:UIView?
override func viewDidLoad() {
func randomizeButtons(){

baseView = UIView(frame:CGRectMake(view.bounds.origin.x + 10, view.bounds.origin.y + 50, view.bounds.size.width, view.bounds.size.height-20))
let viewWidth = baseView.bounds.size.width;
let viewHeight = baseView.bounds.size.height;

baseView.userInteractionEnabled = true
let i = GlobalArrayofUsers.count
var loopCount = 0
while loopCount < i{

let userBaseView = UIView(frame: CGRectMake(abs(CGFloat(arc4random()) % viewWidth - 90) , abs(CGFloat(arc4random()) % viewHeight - 120), 90, 90))
userBaseView.backgroundColor = UIColor.redColor()
userBaseView.userInteractionEnabled = true

userBaseView.layer.cornerRadius = 45
userBaseView.clipsToBounds = true

let button = UIButton(frame: userBaseView.bounds)
button.backgroundColor = UIColor.greenColor()
button.showsTouchWhenHighlighted = true
button.addTarget(self, action: #selector(ViewController.handleTapEventofBtn(_:)), forControlEvents: .TouchUpInside)
button.setTitle("hello", forState: .Normal)
button.userInteractionEnabled = true
print("button frame is\(button.frame)")

loopCount += 1

baseView.subviews.forEach { (users) in
UIView.animateWithDuration(1, delay: 0, options: [.Autoreverse,.Repeat], animations: { += 10
}, completion: nil)
view.insertSubview(baseView, atIndex: view.subviews.count)


func handleTapEventofBtn(sender: UIButton!) {
// handling code

Any idea why my selector method is not called? It is due to animation. How can i handle it.

SOLUTION: Allow userinteraction in UIAnimationOptions


The problem is that you are trying to click an object that is being animated. From the docs:

During an animation, user interactions are temporarily disabled for the views being animated. (Prior to iOS 5, user interactions are disabled for the entire application.)

But worry not, the solution is very easy, just call your animation with the option .AllowUserInteraction. For example (with your code):

UIView.animateWithDuration(1, delay: 0, options: [.Autoreverse,.Repeat,.AllowUserInteraction], animations: { += 10
}, completion: nil)