Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the initial focus on buttons in a view controller running on tvOS (AppleTV)?

I've added some buttons in a Swift game for tvOS.

override func didMoveToView(view: SKView) {

    let button1=UIButton(frame: CGRectMake(330, 800, 300, 100))
    button1(imageBuySelected, forState: UIControlState.Focused)
    button1(imageBuyNormal, forState: UIControlState.Normal
    button1 = UIColor.clearColor()
    button1(self, action: "buy1", forControlEvents: UIControlEvents.PrimaryActionTriggered)
    self.view!.addSubview(button1)

    let button2=UIButton(frame: CGRectMake(330, 800, 300, 100))
    button2(imageBuySelected, forState: UIControlState.Focused)
    button2(imageBuyNormal, forState: UIControlState.Normal
    button2 = UIColor.clearColor()
    button2(self, action: "buy2", forControlEvents: UIControlEvents.PrimaryActionTriggered)
    self.view!.addSubview(button2)

    let button3=UIButton(frame: CGRectMake(330, 800, 300, 100))
    button3(imageBuySelected, forState: UIControlState.Focused)
    button3(imageBuyNormal, forState: UIControlState.Normal
    button3 = UIColor.clearColor()
    button3(self, action: "playGame", forControlEvents: UIControlEvents.PrimaryActionTriggered)
    self.view!.addSubview(button3)
}

When the games starts. The initial focus is set to button1. I want the focus to be set to button3. I understand that the preferred focus is automatically selected based on the first focusable object found starting from the upper left corner of the screen. Does anyone know how override this so I can make button3 the preferredfocusview when the game starts?

like image 243
Dallas Prichard Avatar asked Dec 11 '22 21:12

Dallas Prichard


2 Answers

I hope this is what you were looking for, good luck! :)

override var preferredFocusedView: UIView? {
    get {
        return self.button3
    }
}
like image 171
Hugo Avatar answered Dec 27 '22 10:12

Hugo


In your view or view controller, override the preferredFocusedView method to return button3.

You can read more about this method under the Preferred Focus Chain section of the documentation.

like image 27
Justin Voss Avatar answered Dec 27 '22 11:12

Justin Voss