2016-04-21 67 views
0

我試圖構建我的tvOS UI看起來類似於Apple TV主屏幕。當您專注於應用程序時,會在後臺顯示更大的圖像。 (頂部貨架區域)。問題是,當我調用didUpdateFocusInContext方法時,背景圖像會像它應該那樣更改,但僅在瀏覽collectionviewcell時纔會更改。只要一個,我把重點放在標籤欄,應用程序崩潰與錯誤的:tvOS檢查當前是否聚焦ui元素是一個CollectionViewCell

Could not cast value of type 'UITabBarButton' to CustomCollectionViewCell'.

我想我只是不知道如何檢查是否已聚焦的UI元素是CustomCollectionViewCell。 以下是我有:

func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) { 
     let cell: CustomCollectionViewCell = context.nextFocusedView as! CustomCollectionViewCell 
     let indexPath: NSIndexPath? = self.collectionView.indexPathForCell(cell) 

     mainImageView.image = UIImage(named: images[indexPath!.row]) 
} 

回答

1

這是因爲你是力鑄造context.nextFocusedViewCustomCollectionViewCell。 您可以通過檢查避免崩潰,如果context.nextFocusedView實際上是你所期望的類型,然後才着手做任何你想做的事:

func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) { 
    if let cell = context.nextFocusedView as? CustomCollectionViewCell { 
     let indexPath: NSIndexPath? = self.collectionView.indexPathForCell(cell) 
     mainImageView.image = UIImage(named: images[indexPath!.row]) 
    } 
} 

在一般情況下,要小心當力展開(!)或任何東西強制鑄造as!

相關問題