Programmatically created buttons are not animated on tvOS

Hi,

I understand that several controls (including system buttons) are animated by the focus engine. I created several buttons but they only get white, shaded and a little bigger when they have the focus, however they do not move when you drag your finger and you can not give them a parallax effect.


Please, your help ... thank you very much!


import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

view.backgroundColor = UIColor.white

let button = UIButton(type: .system)

button.setTitle("Btn 1", for: .normal)

button.setTitleColor(UIColor.black, for: .normal)

button.frame = CGRect(x: 500, y: 500, width: 300, height: 100)

view.addSubview(button)

let button2 = UIButton(type: .system)

button2.setTitle("Btn 2", for: .normal)

button2.setTitleColor(UIColor.black, for: .normal)

button2.frame = CGRect(x: 900, y: 500, width: 300, height: 100)

view.addSubview(button2)

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

}

}

Replies

Are you sure UIButtons have that parallax option? I assume that would require 3 images. Not seeing any in your code.

UIButton does not have any parallax effects. If you'd like a button that shifts left to right like in the Movies app check out TVMLKit's buttonLockup.

Actually you can by doing the following:


let myButton = UIButton(type: UIButtonType.custom) as UIButton
myButton.imageView?.clipsToBounds = false
myButton.imageView?.adjustsImageWhenAncestorFocused = true
myButton.adjustsImageWhenHighlighted = true
myButton.setImage(myImage, for: UIControlState.normal)


That would turn a normal UIButton into a buttonLockup with the very same parallax effects 😉

Great example! Just note that this will gimble in all directions whereas `buttonLockup` only translates left and right.