我对 iOS 编程非常陌生,正在尝试从 json 响应中设置 UICollectionView 项目。
这是我的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
[self downloadJSONData];
/* uncomment this block to use subclassed cells */
[self.collectionView registerClass:[CVCell class] forCellWithReuseIdentifier:@"cvCell"];
/* end of subclass-based cells block */
// Configure layout
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(150, 150)];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
[self.collectionView setCollectionViewLayout:flowLayout];
[self.collectionView reloadData];
}
-(void) downloadJSONData {
NSURL *serviceUrl = [[NSURL alloc]initWithString:@"http://myurlhere.com/"];
NSURLRequest *request = [NSURLRequest requestWithURL:serviceUrl];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.data = [[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)responsedata {
[self.data appendData:responsedata];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Error : %@", error);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Succeeded! Received %d bytes of data",[self.data length]);
NSString *txt = [[NSString alloc] initWithData:self.data encoding: NSASCIIStringEncoding];
NSLog(@"response data %@", txt);
self.dictionaryData = [txt JSONValue];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
//NSMutableArray *sectionArray = [self.dataArray objectAtIndex:section];
self.jsonArray = [self.dictionaryData objectForKey:@"images"];
return [self.jsonArray count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
// Setup cell identifier
static NSString *cellIdentifier = @"cvCell";
/* Uncomment this block to use nib-based cells */
// UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
// UILabel *titleLabel = (UILabel *)[cell viewWithTag:100];
// [titleLabel setText:cellData];
/* end of nib-based cell block */
/* Uncomment this block to use subclass-based cells */
CVCell *cell = (CVCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
NSMutableArray *data = [self.dataArray objectAtIndex:indexPath.section];
NSString *cellData = [data objectAtIndex:indexPath.row];
[cell.titleLabel setText:cellData];
/* end of subclass-based cells block */
// Return the cell
return cell;
}
当我运行代码时,它什么也不显示。我想要的是它显示项目并且数量等于数组的计数。还有一件事,关于如何将图像异步加载到集合视图中的任何建议?
我很抱歉我的英语。如果有人可以帮助我,我会很高兴。
谢谢。干杯!