聚焦时(swift)向UIButton添加动作

时间:2015-10-20 17:23:11

标签: swift uibutton tvos

尝试在UIButton聚焦(tvOS)时向其添加动作。

我正在使用

override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
       super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator)

然后:

    if self.button1.focused == true {
    //do something
    }

  if self.button2.focused == true {
    //do something else
    }

这是最好的方法还是会遇到麻烦?

编辑:

您认为这是正确的还是有更好的方法?

 override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
            super.didUpdateFocusInContext(context, withAnimationCoordinator: coordinator)
            coordinator.addCoordinatedAnimations({ () -> Void in

                var previewPlayer = AVPlayer()
                let previewPlayerLayer = AVPlayerLayer(player: previewPlayer)

                previewPlayerLayer.frame = CGRectMake(self.view.frame.size.width/2-128, self.view.frame.size.height/2-254, 254, 128)
                previewPlayer.volume = 0

                 if self.button1.focused == true {

                    let videoURL = NSURL(string: "someString")!
                    previewPlayer = AVPlayer(URL: videoURL)

                }

                if self.button2.focused == true {

                    let videoURL = NSURL(string: "someOtherString")!
                    previewPlayer = AVPlayer(URL: videoURL)

                }


                  previewPlayer.play()


                }) { () -> Void in

            }
        }

1 个答案:

答案 0 :(得分:0)

您可以通过以下两种方式之一了解视图:

//returns bool whether view is focused
someview.focused 

//returns focused view, can return nil
UIScreen.mainScreen().focusedView

任何这些方法都是正确的,不会让你陷入麻烦;)