以编程方式添加UICollectionViewLayout问题

时间:2015-03-16 21:44:54

标签: ios objective-c uicollectionview

我试图在不使用storyBoard的情况下实现this library(实现此库的第一步),因为我以编程方式创建了我的UIcollectionView。

    - (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];

    [_collectionView registerNib:[UINib nibWithNibName:@"myCell" bundle:nil] forCellWithReuseIdentifier:@"cell3"];
    [_collectionView setBackgroundColor:[UIColor colorWithRed:0.945 green:0.945 blue:0.945 alpha:1] ];
    [_collectionView setTransform:CGAffineTransformMakeScale(-1, 1)];

    RFQuiltLayout* layout = (id)[_collectionView collectionViewLayout];
    layout.direction = UICollectionViewScrollDirectionVertical;
    layout.blockPixels = CGSizeMake(100, 100);
}


- (UICollectionView *)collectionView {
    if (!_collectionView) {
        CGRect collectionViewFrame = self.view.bounds;
        collectionViewFrame.size.height -= (self.navigationController.viewControllers.count > 1 ? 0 : (CGRectGetHeight(self.tabBarController.tabBar.bounds))) + 0;
        //        FMMosaicLayout *mosaicLayout = [[FMMosaicLayout alloc] init];
        ////        _collectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:mosaicLayout];
//                RFQuiltLayout* layout = (id)[_collectionView collectionViewLayout];
//                layout.direction = UICollectionViewScrollDirectionVertical;
//                layout.blockPixels = CGSizeMake(100, 100);
        _collectionView = [[UICollectionView alloc] initWithFrame:collectionViewFrame collectionViewLayout:[[RFQuiltLayout alloc] init]];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;

    }
    return _collectionView;
}

但是这并没有奏效,我的视图中没有显示任何内容(没有错误和空视图都是全部)同时使用调试器我已经通知UICollectionView方法永远不会被调用

1 个答案:

答案 0 :(得分:1)

首先,您的collectionView方法未被调用,因为您在viewDidLoad方法中使用_collectionView而不是self.collectionView。你需要为每个属性编写 self 来调用他们的setter和getter方法。

其次,如果你想添加没有XIB故事板的自定义布局,那么你需要以编程方式设置它:

RFQuiltLayout* layout = [[RFQuiltLayout alloc] init];
layout.direction = UICollectionViewScrollDirectionVertical;
layout.blockPixels = CGSizeMake(100, 100);
self.collectionView.collectionViewLayout = layout;