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

How to get Parallax Effect on UIButton in tvOS?

我正在尝试在 UIView 中为 tvOS 应用制作一些 UIButtons,但无法让它们在模拟器中显示新的视差效果。我在 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 的不同参数中设置图像等。但是我无法让按钮进入视差模式并在聚焦时四处移动。

有人知道我需要做什么才能获得所需的视差效果吗?

解决了我的问题 -

UIButtonsetImage 属性 中为 UIControlState.Focused 状态设置 LSR 或 Apple TV 图像堆栈。

UIButton 上设置 imageView?.clipsToBounds = false

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

我得到了以下代码,可以按预期工作:

  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 图像堆栈。