iOS UICollectionView 原型单元格大小属性被忽略 [英] iOS UICollectionView prototype cell size property ignored

查看:15
本文介绍了iOS UICollectionView 原型单元格大小属性被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有两个原型单元格的 UICollectionView.原型单元格具有不同的宽度并包含不同的控件(图像视图和 Web 视图).我肯定会为给定索引返回正确的原型单元格(所有单元格都显示正确的内容),但原型单元格大小被忽略,而是使用集合视图的项目大小.这不像我手动设置大小.如果属性在实际显示时被忽略,那么允许原型单元格在情节提要中调整大小有什么意义?

I'm using a UICollectionView with two prototype cells. The prototype cells have different widths and contain different controls (image view and web view). I'm definitely returning the correct prototype cell for a given index (all the cells display the correct content), but the prototype cell size is ignored and the collection view's item size is used instead. It's not like I'm manually setting the size. What's the point of allowing the prototype cell to be sized in storyboard if the property is just ignored when it's actually displayed?

推荐答案

故事板编辑器中单元格的大小只是为了帮助您设计单元格.由于每个原型单元格的大小可能不同,因此 UICollectionView 不知道为所有单元格选择哪个单元格的大小.这就是为什么您要单独设置要用于单元格的实际大小.您可以在设计器中通过选择集合视图并在集合视图大小"标题下的大小检查器中设置其单元格大小宽度和高度来完成此操作.

The size of the cell in the storyboard editor is just to help you design the cell. Since each prototype cell can be a different size, UICollectionView doesn't know which cell's size to pick for all the cells. That's why you set the actual size you want to use for your cells separately. You can do it in the designer by selecting the collection view and setting its Cell Size Width and Height in the Size inspector, under the "Collection View Size" heading.

或者,您可以覆盖以下方法并返回一个 CGSize 对象,该对象指定您要用于每个单元格的大小.使用这种方法,您实际上可以让每个单元格具有不同的大小:

Or, you can override the following method and return a CGSize object that specifies the size you want to use for each cell. Using this method, you can actually have each cell be a different size:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

例子:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(100, 100);
}

您的视图控制器需要是 UICollectionViewDelegateFlowLayout 的委托才能调用此方法.所以不要忘记将委托声明添加到视图控制器的 .h 文件中,例如:

Your view controller needs to be a delegate of UICollectionViewDelegateFlowLayout in order for this method to be called. So don't forget to add that delegate declaration to your view controller's .h file, such as:

@interface MyViewController () <UICollectionViewDelegateFlowLayout>

斯威夫特

extension MyViewController : UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 100)
    }
}

这篇关于iOS UICollectionView 原型单元格大小属性被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆