Preston Price Preston Price - 5 months ago 41
Swift Question

Trigger a UIPress programmatically with tvOS

I am trying to trigger a UIPress on my button in tvOS programmatically so that I can get the same animation a user receives when they click on a button. I have tried this:

// This is Swift 3 but a Swift 2 answer or even Objective-C is fine
button.sendActions(for: UIControlEvents.touchUpInside)


The command performs a click on the button, but the animation of the focused button being pressed down is not performed.

Answer

You could animate the UIButton. You should use .PrimaryActionTriggered instead of .touchUpInside also. For example:

let animationDuration = 0.2
let focusedScaleFactor: CGFloat = 1.2
UIView.animateWithDuration(animationDuration, animations: {
    button.transform = CGAffineTransformMakeScale(focusedScaleFactor, focusedScaleFactor)
    }) { (finished) in
        UIView.animateWithDuration(animationDuration, animations: {
            button.transform = CGAffineTransformIdentity
        }) { (finished) in
            button.sendActions(for: .PrimaryActionTriggered)
        }
}