我是tvOS应用程序的新手。我在UICollectionView
UICollectionViewCell
中创建了一个自定义按钮。当我加载视图控制器时,我将焦点转到 UICollectionView 的第一个单元格,但通过按键盘上的下一个键,焦点不会移动到下一个单元格。
我的UICollectionView中有六个不需要滚动的单元格,这意味着这些单元格在UICollectionView的宽度内正确适合。对于六个单元格,我无法将焦点移动到下一个单元格。但是,如果我向 UICollectionView 再添加一个单元格,焦点就会正确移动到下一个单元格。我不确定发生了什么。谁能帮我解决这个问题?
谢谢
我在嵌套集合视图中也有这个。对我来说,问题是内部集合视图没有覆盖-(BOOL)canBecomeFocus
并返回NO
。
帮助我调试此问题的是打开视图层次结构,获取未聚焦的视图地址(通过右键单击视图的打印说明)并调用po [<view address> _whyIsThisViewNotFocusable]
,这很可能会告诉您问题所在。就我而言,它读到:
Printing description of $3:
<_UIStackedImageContainerView: 0x7f9404604630; frame = (0 0; 308 308); layer = <_UIStackedImageContainerLayer: 0x7f94046047d0>>
(lldb) po [0x7f9404604630 _whyIsThisViewNotFocusable]
ISSUE: This view returns NO from -canBecomeFocused.
ISSUE: One or more ancestors have issues that may be preventing this view from being focusable. Details:
<StationCollectionViewCell 0x7f940434c6c0>:
ISSUE: This view returns YES from -canBecomeFocused, which will prevent its subviews from being focusable.
<StationSectionCollectionViewCell 0x7f940403e8e0>:
ISSUE: This view returns YES from -canBecomeFocused, which will prevent its subviews from being focusable.
在 Swift 中
如果要聚焦集合视图单元格,则可以使用集合视图委托方法,方法名称为
func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator)
{
}
你可以像这样使用这种方法...
func collectionView(collectionView: UICollectionView, didUpdateFocusInContext context: UICollectionViewFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
if let previousIndexPath = context.previouslyFocusedIndexPath,
let cell = collectionView.cellForItemAtIndexPath(previousIndexPath) {
cell.contentView.layer.borderWidth = 0.0
cell.contentView.layer.shadowRadius = 0.0
cell.contentView.layer.shadowOpacity = 0
}
if let indexPath = context.nextFocusedIndexPath,
let cell = collectionView.cellForItemAtIndexPath(indexPath) {
cell.contentView.layer.borderWidth = 8.0
cell.contentView.layer.borderColor = UIColor.blackColor().CGColor
cell.contentView.layer.shadowColor = UIColor.blackColor().CGColor
cell.contentView.layer.shadowRadius = 10.0
cell.contentView.layer.shadowOpacity = 0.9
cell.contentView.layer.shadowOffset = CGSize(width: 0, height: 0)
collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: [.CenteredHorizontally, .CenteredVertically], animated: true)
}
}