Search code examples
swifttvostvml

Can we stop or remove animation effect on focus with UIButton and give other border effect tvOS


In the below delegate function I was trying to do but did'nt get desired result

override func didUpdateFocusInContext(context: UIFocusUpdateContext,withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
    if (context.nextFocusedView == self) {
        coordinator.addCoordinatedAnimations({ () -> Void in
            self.animationDidStop(CAAnimation(), finished: true)
            }, completion: { () -> Void in

        })

    }
    else {
        // handle unfocused appearance changes

        coordinator.addCoordinatedAnimations({ () -> Void in
            self.animationDidStop(CAAnimation(), finished: true)
            }, completion: { () -> Void in

        })
    }
    context.nextFocusedView?.layer.shadowOffset = CGSizeZero
    context.nextFocusedView?.layer.shadowOpacity = 0.9;
    context.nextFocusedView?.layer.shadowRadius = 0;
    context.nextFocusedView?.layer.shadowColor= UIColor.orangeColor().CGColor
    context.previouslyFocusedView?.layer.shadowOpacity = 0;
}

Solution

  • First of all you have to set your button type to Custom type. By custom type you will get no more system animations, so you have to do all animations by yourself.

    Then you can implement didUpdateFocusInContext method either in UIViewController or you can make your own UIButton subclass if there are more button types on a single screen.

    Here is a code that I use in my UIButton subclass. This will provide the button enlargement along with red border on focus and will get to normal state on focus loss.

    let scale = 1.1    
    layer.borderColor = UIColor.redColor().CGColor
    
    override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
    
        if context.nextFocusedView == self {
            coordinator.addCoordinatedAnimations({ () -> Void in
    
                self.transform = CGAffineTransformMakeScale(scale, scale)
                self.layer.borderWidth = 2
    
                }, completion: nil)
        }
        else {
            coordinator.addCoordinatedAnimations({ () -> Void in
    
                self.transform = CGAffineTransformIdentity
                self.layer.borderWidth = 0
    
                }, completion: nil)
        }
    }