我已经UICollectionView
拉伸了整个屏幕宽度。我的UICollectionViewCell
s 是从MyViewCell.xib
. 我通过以下方式设置其大小:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(CGRectGetWidth(collectionView.frame) * 0.5, CGRectGetHeight(collectionView.frame));
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 16;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MyViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath];
return cell;
}
在主视图控制器加载期间,我有:
[self.collView registerNib:[UINib nibWithNibName:@"MyViewCell" bundle:nil] forCellWithReuseIdentifier:@"myCell"];
self.collView.delegate = self;
self.collView.dataSource = self;
这使得“单元格视图”具有正确的大小,但其从 XIB 加载的内容仍然“小”且未拉伸。这意味着,我可以在屏幕上看到两个项目,但它们不是 strechtech,仅向左对齐并且固定宽度约为 50。
如果我在 iPhone 上使用相同的代码,它就可以正常工作,只有 iPad 有问题。两台设备都有相同的 iOS 版本 (10.3.3)。
给定的代码可以正常工作。我将它翻译成 Swift 如下(这是我的视图控制器的全部代码:
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var cv: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.cv.register(UINib.init(nibName: "MyViewCell", bundle: nil), forCellWithReuseIdentifier: "cell")
self.cv.delegate = self
self.cv.dataSource = self
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 16
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = cv.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.layer.borderWidth = 2
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width:self.cv.bounds.width/2, height:self.cv.bounds.height)
}
}
这是我在 iPad 模拟器上看到的:
考虑到默认的项目间距为 10,这正是我希望看到的。
MyViewCell 笔尖只包含一个小的黄色单元格。为了清楚起见,我添加了边框。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句