我正在使用新闻源创建一个应用程序作为UICollectionView但是当我更改JSON文件时它似乎没有更新。我正在使用UIRefreshControl来刷新它,但是我无法判断我的问题是与此有关,还是与JSON的读取方式有关(或完全不同)。
- (void)viewDidLoad
{
[super viewDidLoad];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.navigationItem.title = @"News";
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(0,0,23,16);
[btn setBackgroundImage:[UIImage imageNamed:@"menuImage.png"] forState:UIControlStateNormal];
[btn addTarget:(NavigationViewController *)self.navigationController action:@selector(showMenu) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:btn];
self.navigationItem.leftBarButtonItem = barBtn;
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config
delegate:self
delegateQueue:nil];
[self fetchFeed];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat frameWidth = screenRect.size.width - 20;
CGFloat frameHeight = screenRect.size.height - 20;
_collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(10, 10, frameWidth, frameHeight) collectionViewLayout:layout];
[_collectionView setDataSource: self];
[_collectionView setDelegate: self];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[_collectionView setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:_collectionView];
UIRefreshControl * refreshControl = [[UIRefreshControl alloc] init];
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:@"Refresh Images"];
[_collectionView addSubview:refreshControl];
[refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.collectionView reloadItemsAtIndexPaths:[self.collectionView indexPathsForVisibleItems]];
[self.collectionView reloadData];
}
- (void)fetchFeed
{
NSString *requestString = @"http://www.jameslester.xyz/example.json";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
self.articles = jsonObject[@"articles"];
NSLog(@"%@", self.articles);
NSLog(@"Feed Fetched!!!");
dispatch_async(dispatch_get_main_queue(), ^{[self.collectionView reloadData];
});
}];
[dataTask resume];
}
- (void)refresh:(id)sender
{
[self fetchFeed];
[(UIRefreshControl *)sender endRefreshing];
NSLog(@"Refreshed");
}
任何帮助都将非常感激。
#define LABEL_TAG 100001
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
UILabel *articleTitle = [cell.contentView viewWithTag:LABEL_TAG];
NSDictionary *article = self.articles[indexPath.row];
if (!articleTitle) {
articleTitle = [[UILabel alloc]initWithFrame:CGRectMake(5, cell.bounds.size.height - cell.bounds.size.height / 2.2, cell.bounds.size.width - 10, cell.bounds.size.height / 2)];
articleTitle.textColor = [UIColor whiteColor];
articleTitle.numberOfLines = 3;
articleTitle.adjustsFontSizeToFitWidth = YES;
articleTitle.tag = LABEL_TAG;
[cell.contentView addSubview:articleTitle];
}
articleTitle.text = article[@"title"];
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: article[@"image"]]];
UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:imageData]];
[bgImageView setContentMode:UIViewContentModeScaleAspectFill];
[bgImageView setClipsToBounds:YES];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(0, cell.bounds.size.height - cell.bounds.size.height / 2, cell.bounds.size.width, cell.bounds.size.height/2);
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor clearColor] CGColor], (id)[[UIColor blackColor] CGColor], nil];
//gradient.locations = [NSArray arrayWithObjects:[NSNumber numberWithInt:0.0],[NSNumber numberWithInt:0.5], nil];
[bgImageView.layer insertSublayer:gradient atIndex:0];
cell.backgroundView = bgImageView;
return cell;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionView *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
return 10; // This is the minimum inter item spacing, can be more
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 10;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
int x = screenWidth/2 - 15;
int y = x;
return CGSizeMake(x, y);
}
- (void)collectionView:(UICollectionView *)colView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
NSDictionary *article = self.articles[indexPath.row];
NSURL *URL = [NSURL URLWithString:article[@"url"]];
self.webViewController.title = article[@"title"];
self.webViewController.URL = URL;
[self.navigationController pushViewController:self.webViewController
animated:YES];
}
答案 0 :(得分:0)
尝试这个
- (void)fetchFeed {
NSString *requestString = @"http://www.jameslester.xyz/example.json";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest*req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask*dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.articles = jsonObject[@"articles"];
NSLog(@"%@", self.articles);
NSLog(@"Feed Fetched!!!");
dispatch_async(dispatch_get_main_queue(), ^{
[_collectionView reloadData];
});
}];
[dataTask resume];
}
答案 1 :(得分:0)
如果NSLog(@"%@", self.articles)
正常工作并显示数据,则表明您已获得网络数据。您是否正确设置了UIView作为委托和数据源?这通常在UIViewController类的顶部完成,如下所示:
class MyClassName: UICollectionViewDataSource {
// Your code here.
}
检查数据源是否设置正确的一种方法是在此处设置断点
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
print(“This shows that I’m getting called”)
// Your custom code
}
致电时
dispatch_async(dispatch_get_main_queue(), ^{
[self.collectionView reloadData];
})
这将依次调用cellForItemAtIndexPath来显示数据。如果未调用cellForItemAtIndexPath,那么您尚未正确设置UICollectionViewDataSource