以编程方式创建的UICollectionView不会滚动

时间:2012-10-02 21:00:21

标签: ios uicollectionview

我正在使用UICollectionView制作水平选择器。这很简单:UIView以编程方式创建UICollectionView,使用UICollectionViewFlowLayout一个部分,滚动设置为水平。它出现在屏幕上,在正确的单元格中显示正确的数据。但它不会滚动 - 事实上它根本不会响应用户交互。

以下是视图的初始化程序:

- (id)initWithFrame:(CGRect)frame andItemData:(NSArray *)itemData
{
    self = [super initWithFrame:frame];
    if (self) {
        _itemData = itemData;

        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        [flowLayout setItemSize:CGSizeMake(kCellWidth, kCellHeight)];
        [flowLayout setMinimumInteritemSpacing:0.f];
        [flowLayout setMinimumLineSpacing:0.f];

        _collectionView = [[UICollectionView alloc] initWithFrame:[self frame] collectionViewLayout:flowLayout];
        [_collectionView setDataSource:self];
        [_collectionView setDelegate:self];
        [_collectionView setBounces:NO];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"HorizontalPickerCell"];
        [self addSubview:_collectionView];
    }
    return self;
}

我尝试以编程方式将UserInteractionEnabled设置为YES,但这没有任何区别(也不应该有,因为默认情况下UserInteractionEnabled设置为YES 。 FWIW,集合视图使用标准UICollectionViewCell,并将UILabel添加到contentView s作为子视图。

有没有想过为什么这不滚动?任何和所有的帮助非常感谢。

1 个答案:

答案 0 :(得分:6)

好吧,这对我来说既愚蠢又容易修复。我将集合视图的框架设置为其父视图frame而不是bounds。这导致了各种自动布局问题,导致触摸事件无法注册。现在全部修好了。