我使用UICollectionView(flowlayout)来构建简单的布局。 每个单元格的宽度设置为使用的屏幕宽度self.view.frame.width
Swift:如何在设备旋转后刷新UICollectionView布局
但是当我旋转设备时,单元格不会更新。
我找到了一个功能,它是在方向变化称为:
override func willRotateToInterfaceOrientation(toInterfaceOrientation:
UIInterfaceOrientation, duration: NSTimeInterval) {
//code
}
,但我无法找到一个方法来更新UICollectionView布局
主要代码这里:
class ViewController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{
@IBOutlet weak var myCollection: UICollectionView!
var numOfItemsInSecOne: Int!
override func viewDidLoad() {
super.viewDidLoad()
numOfItemsInSecOne = 8
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
//print("orientation Changed")
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numOfItemsInSecOne
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellO", forIndexPath: indexPath)
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
let itemSize = CGSize(width: self.view.frame.width, height: 100)
return itemSize
}}
感谢@ khuong291如果我没有我的CollectionView的对象,我有UICollectionViewController?我将如何调用reloadData? –
UICollectionViewController已经具有'collectionView'属性,所以你只要按照我所说的调用它们。只需将它们编辑为'collectionView.reloadData()'。它会工作。 – Khuong
所以你需要重新加载视图,你不能只是触发布局刷新? – Rivera