我有一個UICollectionView,它由彈出窗口顯示。 UICollectionView包含16行,每行10個單元格,我希望單元格填充UICollectionView的寬度。我試圖調整viewWillTransitionToSize中每個單元格的大小,但我無法獲得正確的值。如何在viewWillTransitionToSize後獲取子視圖的大小
如何獲得UICollectionView的寬度,因爲它將在之後轉換?在iPad上航2
從70/30到50/50 50/50改變至70/30分屏之間切換時
的問題顯示出來給我太小細胞:
從50/50到70/30改變給了我太大細胞:
當前代碼:
class ColorPickerCollectionViewController: UICollectionViewController {
var cellsize:CGSize?;
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
if let flowLayout = self.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.minimumInteritemSpacing = 0;
flowLayout.minimumLineSpacing = 0;
flowLayout.sectionInset = UIEdgeInsetsMake(0,0,0,0);
}
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 16;
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10;
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell
// Configure the cell
let colorView = getColorViewForCell(indexPath, cell: cell);
cell.contentView.addSubview(colorView);
cell.selectedBackgroundView = UIView();
cell.selectedBackgroundView!.backgroundColor = UIColor.whiteColor();
return cell
}
func getColorViewForCell(indexPath:NSIndexPath, cell:UICollectionViewCell) -> UIView {
let colorView = UIView();
colorView.backgroundColor = UIColor.blueColor();
colorView.frame = CGRectMake(cell.bounds.origin.x + 1, cell.bounds.origin.y + 1, cell.bounds.width - 2, cell.bounds.height - 2);
colorView.translatesAutoresizingMaskIntoConstraints = false;
return colorView;
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if self.cellsize == nil {
let width = CGFloat(collectionView.frame.width/10);
cellsize = CGSize(width: width, height: width);
}
return self.cellsize!;
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
NSLog("viewWillTransitionToSize")
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator);
//What do I do here?
self.cellsize //= ???;
let cView:UICollectionView = self.collectionView!;
cView.performBatchUpdates(nil, completion: nil);
}
}
你試過繼承'UICollectionViewFlowLayout'並覆蓋'FUNC shouldInvalidateLayoutForBoundsChange(_ newBounds:的CGRect) - > Bool'返回true? –
@MikePollard感謝這個想法,我必須在本週末嘗試。 – Lizzan
@MikePollard非常感謝您帶領我朝着正確的方向前進。我將我的單元大小計算轉移到FlowLayout子類中,最終使所有工作都成功。 – Lizzan