Fabian Boulegue Fabian Boulegue - 10 months ago 69
Swift Question

tvOS Button Action

I create a UIButton in tvOS via Swift

let randomBtn = UIButton()
randomBtn.setTitle("Zufällig", forState: .Normal)
let RndNormal = UIImage(named: "RndNormal")
let RndHoover = UIImage(named: "RndHoover")
randomBtn.setImage(RndNormal, forState: .Normal)
randomBtn.setImage(RndHoover, forState: .Focused)
randomBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
randomBtn.setTitleColor(UIColor.whiteColor(), forState: .Focused)

randomBtn.addTarget(self, action: #selector(ViewController.click(_:)), forControlEvents: UIControlEvents.TouchUpInside)

let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
randomBtn.frame = CGRect(x: screenWidth - 150, y: 60 , width: 70 , height: 70)

func click(sender: UIButton) {

But the action never get fired if I press the button, is there anything different in tvOS?


In tvOS for Button action UIControlEvents TouchUpInside will not call.

You have to use UIControlEvents PrimaryActionTriggered like below.

randomBtn.addTarget(self, action: #selector(ViewController.click(_:)), forControlEvents: UIControlEvents. PrimaryActionTriggered)

Also Refer this link if you have any confusion