Aym*_*ATH 4 focus apple-tv uicollectionview tvos
我需要指定哪个单元格应该获得焦点.
根据Apple文档,indexPathForPreferredFocusedView如果remembersLastFocusedIndexPath属性是false,或者如果没有保存的索引路径,则应调用委托方法,因为之前没有单元格.
在我的情况下,我在a中使用集合视图UIViewController并设置remembersLastFocusedIndexPath为false但indexPathForPreferredFocusedView未被调用.
怎么解释这个行为?
小智 6
You should set remembersLastFocusedIndexPath to true.
collectionView.remembersLastFocusedIndexPath = true
Run Code Online (Sandbox Code Playgroud)
该函数indexPathForPreferredFocusedView是UICollectionViewDelegate的一部分,因此可能是委托未分配给collectionView.
或者,问题也可能出在焦点环境中,而不考虑您的UICollectionView.
作为参考,这里有一个简单的collectionView示例,其中包含5个单元格,默认情况下最初选中的单元格
import UIKit
class ViewController: UIViewController {
private var collectionView: UICollectionView!
private var items = ["One", "Two", "Three", "Four", "Five"]
override var preferredFocusEnvironments: [UIFocusEnvironment] {
return [collectionView]
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.remembersLastFocusedIndexPath = false
MyCell.register(in: collectionView)
view.addSubview(collectionView)
collectionView.dataSource = self
collectionView.delegate = self
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MyCell.reuseIdentifier, for: indexPath) as! MyCell
cell.titleLabel.text = items[indexPath.row]
return cell
}
}
extension ViewController: UICollectionViewDelegate {
func indexPathForPreferredFocusedView(in collectionView: UICollectionView) -> IndexPath? {
return IndexPath(row: 2, section: 0)
}
}
class MyCell: UICollectionViewCell {
static var reuseIdentifier: String { return String(describing: self) + "ReuseIdentifier" }
var titleLabel: UILabel!
public static func register(in collectionView: UICollectionView) {
collectionView.register(MyCell.self, forCellWithReuseIdentifier: MyCell.reuseIdentifier)
}
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel = UILabel(frame: bounds)
backgroundColor = .blue
contentView.addSubview(titleLabel)
}
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
backgroundColor = isFocused ? .red : .blue
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2014 次 |
| 最近记录: |