在Code中创建UICollectionView时遇到问题,与在Storyboard中创建View相比。在以编程方式创建的视图中,我无法更改焦点,因为它在故事板版本中按预期工作。
这是我创建UICollectionView
的方法class ChannelGridViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
func setup() {
let layout : UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50)
layout.itemSize = CGSize(width: 350, height: 225)
let grid = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
grid.dataSource = self
grid.delegate = self
grid.userInteractionEnabled = true
grid.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
self.view.addSubview(grid)
}
设置方法是我添加到编程部分的唯一附加方法。
其余方法如下:
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, canFocusItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)
cell.backgroundColor = .greenColor()
cell.userInteractionEnabled = true
cell.clipsToBounds = false
return cell
}
func collectionView(collectionView: UICollectionView, shouldUpdateFocusInContext context: UICollectionViewFocusUpdateContext) -> Bool {
return true
}
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
if (context.nextFocusedView != nil) {
coordinator.addCoordinatedAnimations({() -> Void in
context.nextFocusedView!.transform = CGAffineTransformMakeScale(1.05, 1.05)
}, completion: { _ in })
}
if (context.previouslyFocusedView != nil) {
coordinator.addCoordinatedAnimations({() -> Void in
context.previouslyFocusedView!.transform = CGAffineTransformMakeScale(1.0, 1.0)
}, completion: { _ in })
}
}
我希望你们可以帮助我,因为经过长时间的谷歌搜索和堆栈溢出之后我无法找到问题。 99%的教程都是关于故事板的。
非常感谢, 亚历