如何在没有Storyboard的情况下加载CollectionView
问题描述:
我是iOS开发新手。我需要使用CollectionView而不使用Storyboard,并且此视图必须加载到选项卡中。这可能吗。如何在没有Storyboard的情况下加载CollectionView
谢谢
答
雅。你可以创建编程
-(void)loadView
{
[super loadView];
UICollectionViewFlowLayout *layout= [[UICollectionViewFlowLayout alloc]init];
self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
self.collectionView.delegate=self;
self.collectionView.dataSource=self;
[self.collectionView setAutoresizingMask:UIViewAutoresizingFlexibleHeight |UIViewAutoresizingFlexibleWidth| UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin];
[self.collectionView setBackgroundColor:[UIColor clearColor]];
[self.collectionView registerClass:[UICollectionViewCell class]
forCellWithReuseIdentifier:@"Cell"];
[self.view addSubView:self.collectionView];
}
答
你必须创建一个实现UICollectionViewDataSource和UICollectionViewDelegate这样的UIViewController子类:
@interface MyViewController:UIViewController<UICollectionViewDelegate, UICollectionViewDataSource>
@end
然后在.M文件你实现所需的UICollectionViewDataSource和UICollectionViewDelegate方法
并覆盖 - [UIViewController viewDidLoad]像这样:
- (void)viewDidLoad {
[super viewDidLoad];
UICollectionView *collectionView = [UICollectionView alloc] initWithFrame:self.view.bounds];
collectionView.delegate = self;
collectionView.dataSource = self;
[self.view addSubview:collectionView];
}
查看更多此处http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UICollectionView_class/Reference/Reference.html – 2013-03-15 05:15:46