UICollectionView created programmatically doesn

2019-04-11 12:07发布

问题:

I'm making a horizontal picker by using a UICollectionView. It's simple enough: A UIView with a UICollectionView created programmatically, using UICollectionViewFlowLayout with one section, scrolling set to horizontal. It appears onscreen, complete with the correct data in the correct cells. But it doesn't scroll---in fact it doesn't respond to user interaction at all.

Here's the initializer for the view:

- (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;
}

I tried programmatically setting UserInteractionEnabled to YES, but that didn't make any difference (nor should it have, since UserInteractionEnabled is set to YES by default). FWIW, the collection view uses standard UICollectionViewCells with UILabels added to their contentViews as subviews.

Any thought as to why this isn't scrolling? Any and all help much appreciated.

回答1:

Ok, this turned out to be both dumb on my part and easy to fix. I set the frame of the collection view to its parent view's frame rather than its bounds. This caused all sorts of autolayout issues and resulted in touch events simply not registering. All fixed now.