Fabian Boulegue Fabian Boulegue - 4 months ago 21
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)
self.view.addSubview(randomBtn)



func click(sender: UIButton) {
print("click")
}


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

Answer

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

https://forums.developer.apple.com/thread/17925