如何在tvOS中获得对UIButton的视差效果?

时间:2016-02-09 01:16:27

标签: swift parallax tvos

我正试图在UIButtons中为tvOS应用制作一些UIView,但无法让它们在模拟器中显示新的视差效果。我成功地在images.xcassets中设置了一个名为“startReadingButton”的电视图像堆栈,并且我的按钮加载了文件,但是当在模拟器中在遥控器上滑动时,它们不会显示闪亮的视差效果。以下是我加载UIButtons的方法:

   for button in 1...5 {

        let image = UIImage(named: "startReadingButton")

        let newButton = UIButton(type: .Custom)
        newButton.frame = buttonRects[button - 1]
        newButton.setBackgroundImage(image, forState: UIControlState.Focused)
        newButton.imageView?.image = image
        newButton.imageView?.adjustsImageWhenAncestorFocused = true
        newButton.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.PrimaryActionTriggered)
        newButton.tag = button
        newButton.canBecomeFocused()
        newButton.adjustsImageWhenHighlighted = true
        newButton.clipsToBounds = false
        self.addSubview(newButton)
        self.homeButtons.append(newButton)

    }

到目前为止,我已经尝试了几乎所有可以想到的变体来找到解决方案,比如将按钮类型设置为.Custom和.System,在UIButton的不同参数中设置图像等。但是我无法获得按钮进入视差模式并在聚焦时移动。

任何人都知道我需要做些什么来获得所需的视差效果?

1 个答案:

答案 0 :(得分:0)

解决了我的问题 -

UIButton setImage UIControlState.Focused属性中设置您的LSR或Apple TV图像堆栈。

imageView?.clipsToBounds = false上设置UIButton

newButton.imageView?.adjustsImageWhenAncestorFocused = true上设置UIButton

我有以下代码按预期工作:

  for button in 1...3 {

        let buttonUnpressedTexture = UIImage(contentsOfFile:NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("startReadingUnpressed.png"))!
        let buttonPressedTexture = UIImage(contentsOfFile:NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("startReadingPressed.png"))!

        let newButton = UIButton(type: .Custom)
        newButton.frame = buttonRects[button - 1]
        newButton.setImage(buttonUnpressedTexture, forState: UIControlState.Normal)
        newButton.setImage(buttonPressedTexture, forState: UIControlState.Highlighted)
        newButton.setImage(UIImage(named: "StartReadingButton"), forState: UIControlState.Focused)
        newButton.imageView?.clipsToBounds = false
        newButton.imageView?.adjustsImageWhenAncestorFocused = true
        newButton.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.PrimaryActionTriggered)
        newButton.tag = button
        newButton.canBecomeFocused()
        self.addSubview(newButton)            
    }

" StartReadingButton"是我的images.xcassets目录中的Apple TV图像堆栈。