私のiPhoneアプリでは、コレクションビューに画像を表示しています。URLから画像を取得し、URLを使用して画像サイズも取得します。例:- 横向きと縦向きの 2 種類の画像があるとします。縦向きの画像では値 P を、横向きの画像では L を取得します。
collectionView セルのサイズをカスタマイズするには?
私のiPhoneアプリでは、コレクションビューに画像を表示しています。URLから画像を取得し、URLを使用して画像サイズも取得します。例:- 横向きと縦向きの 2 種類の画像があるとします。縦向きの画像では値 P を、横向きの画像では L を取得します。
collectionView セルのサイズをカスタマイズするには?
1) 複数のレイアウト オブジェクトを維持して交換することもできますが、もっと簡単な方法があります。以下を UICollectionViewController サブクラスに追加し、必要に応じてサイズを調整します。
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
// Adjust cell size for orientation
if (UIDeviceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) {
return CGSizeMake(170.f, 170.f);
}
return CGSizeMake(192.f, 192.f);
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[self.collectionView performBatchUpdates:nil completion:nil];
}
呼び出す-performBatchUpdates:completion:
と、レイアウトが無効になり、アニメーションでセルのサイズが変更されます (実行する追加の調整がない場合は、両方のブロック パラメーターに nil を渡すだけでかまいません)。
2) 項目のサイズを にハードコーディングする代わりに-collectionView:layout:sizeForItemAtIndexPath
、collectionView の境界の高さまたは幅を、画面に収めたいセルの数で割るだけです。水平にスクロールする場合は高さを使用し、UICollectionView
垂直にスクロールする場合は幅を使用します。
フローレイアウトをviewcontrollerにすばやく拡張するには、セルに動的な画像を表示する必要がある場合は、画像名をビューコントローラーに保持する変数を作成し、これを使用します。
let imageData = ["image1","image2","image3","image4"]
extension yourViewController: UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let photo = UIImage(named: imageData[indexPath.row])
return CGSize(width: (photo?.size.width)!, height: (photo?.size.height)!)
}
}