我正在尝试获取具有背景图像和文本的集合视图单元格。当我构建并运行它时,它们有时会出现在模拟器中,有时甚至不会出现在我不更改代码的情况下。
- (void)viewDidLoad
{
[super viewDidLoad];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat frameWidth = screenRect.size.width - 40;
CGFloat frameHeight = screenRect.size.height - 20;
_collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(20, 20, frameWidth, frameHeight) collectionViewLayout:layout];
[_collectionView setDataSource: self];
[_collectionView setDelegate: self];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[_collectionView setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:_collectionView];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [self.articles count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
UILabel *articleTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, cell.bounds.size.width, 40)];
NSDictionary *article = self.articles[indexPath.row];
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: article[@"image"]]];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:imageData]];
articleTitle.text = article[@"title"];
articleTitle.textColor = [UIColor whiteColor];
[cell.contentView addSubview:articleTitle];
return cell;
}“文章”是一个带有标题、图片和url键的json对象。当细胞出现时,它们似乎起作用了,但正如我所说的,它们并不总是出现。
这是我的第一个应用程序,所以任何帮助都会非常感谢。
发布于 2015-12-04 04:05:05
栏目的数量将取决于文章数量。尝试在其中放置断点,您的文章数组可能为空,如果是这样,集合视图数据源将不会获得任何要显示的数据。或者,如果self.articel引用数组,则尝试将行NSDictionary *文章= self.articlesindexPath.row;替换为NSDictionary *文章= self.articles objectatIndexPath:indexPath.row;
或者发布你的完整代码,这样我们就可以看到其他可能的bug。
https://stackoverflow.com/questions/34071710
复制相似问题