I'm trying to adjust height of UITableViewCell based on content after getting JSON data.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
I've added like that but UITableViewCell height cannot be increased based on content. Please help me how to solve.
- (void) getAllocatedJobs {
_allTableData = [[NSMutableArray alloc]init];
[SVProgressHUD show];
dispatch_queue_t getInit = dispatch_queue_create("getinit",NULL);
dispatch_async(getInit, ^{
NSDictionary *jsonResponse = [commClass getJobs:strDriverId paramJobType:#""];
NSNumber *status = [jsonResponse valueForKey:#"Success"];
NSString *message = [jsonResponse valueForKey:#"Message"];
NSArray *dataArray = [jsonResponse valueForKey:#"lstJob"];
dispatch_async(dispatch_get_main_queue(), ^{
if([status intValue] == 1) {
for(int i=0; i<[dataArray count]; i++) {
NSDictionary *JobData = [dataArray objectAtIndex:i];
[_allocatedTable reloadData];
} else {
[commClass showAlert:APP_NAME alertMessage:message];
[SVProgressHUD dismiss];
}
});
});
}
if you want to use UITableViewAutomaticDimension then don't return it in heightForRowAtIndexPath.Do it in viewDidload like,
tableView.estimatedRowHeight = 100.0
tableView.rowHeight = UITableViewAutomaticDimension
and autolayout is mandatory for UITableViewAutomaticDimension so make sure that you have set proper constraints. and reload table data when you get all json data successfully if needed.
Hope this will help :)
Try to calculate the height based on the content in this method:-
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
Related
I started an iOS project and I'm working with UITableView to display a list of pilots with images . I did pagination on my api and I tried to load more once you scrolled the tableview. the problem that I got is that the new cells are always displayed on top of the tableview not in the bottom. Please check on my code if there is a solution I will be grateful
- (void)loadData :(NSInteger)page {
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#%#%ld",NSLocalizedString(#"get_pilots",nil),mainDelegate.idAccount,#"?page=",(long)page]];
task = [restObject GET:url :mainDelegate.token completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary* jsonResponse = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:nil];
NSArray *pilotKey = [jsonResponse objectForKey:#"pilot"];
for (NSDictionary *pilotItem in pilotKey ){
PilotObject *pilotObj = [PilotObject new];
[pilotObj getPilot:pilotObj :pilotItem];
[_pilotsAll addObject:pilotObj];
}
dispatch_async(dispatch_get_main_queue(), ^{
[hud hideAnimated:YES];
[self checkTableView:_pilotsDisplay :self.view];
[viewPilots.tableViewPilots reloadData];
});
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (currentPage == totalPages) {
return [_pilotsDisplay count];
}
return [_pilotsDisplay count] + 1;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == [_pilotsDisplay count] - 1 && currentPage<totalPages ) {
[self loadData:++currentPage];
NSLog(#"current page : = %ld",(long)currentPage);
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == [_pilotsDisplay count]) {
static NSString *identifier = #"PilotCellTableViewCell";
PilotCellTableViewCell *cell = (PilotCellTableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
cell.hidden=YES;
UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView *)[cell.contentView viewWithTag:100];
[activityIndicator startAnimating];
return cell;
} else {
PilotObject *pilotObjDisplay = nil;
pilotObjDisplay = [_pilotsDisplay objectAtIndex:[_pilotsDisplay count]-1-indexPath.row];
static NSString *identifier = #"PilotCellTableViewCell";
PilotCellTableViewCell *cell = (PilotCellTableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
cell.hidden=NO;
cell.image.image = pilotObjDisplay.imageDisplayPilot;
cell.titleLabel.text = pilotObjDisplay.firstName;
cell.subTitleLabel.text = pilotObjDisplay.lastName;
cell.backgroundColor = [UIColor colorWithHexString:NSLocalizedString(#"gray_background", nil)];
return cell;
}
return nil;
}
Why you are taking 2 array _pilotsDisplay and _pilotsAll ?
If not necessary then you can also do pagination using one NSMutableArray which you can use in both cases while fetching data from server as well as while filling data to UITableView.
Remember one thing only initialise your NSMutableArray in viewDidLoad method. And when you received new data use addObject method of NSMutableArray which you are already using. And then call reloadData method of UITableView.
And in cellForRowAtIndexPath don't use calculation like [_pilotsDisplay count]-1-indexPath.row, simply use indexPath.row.
Here, inserting rows to the tableview may help you.
[tableView beginUpdates];
NSArray *paths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:[dataArray count]-1 inSection:1]];
[[self tableView] insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationTop];
[tableView endUpdates];
You shouldn't add cells to a tableview. what you should do is add data to the tableview's datasource (in your case, _pilotsDisplay) and then simply reload the table. If you want the new data to appear at bottom or in any particular order, you should do that to your datasource (the array).
i'm trying to do a weather application
#import "LocationTableViewController.h"
#interface LocationTableViewController (){
NSArray *hourlyData;
NSArray *dailyData;
}
#end
#implementation LocationTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *str = #"https://api.forecast.io/forecast/cd8edc928426f2ac3e341441c7a9c6d3/37.8267,-122.423";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
NSDictionary *dataFromWeb = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
i took a json query that gives hourly and daily data, then converted it into dictionary. Here i created two dictionaries ie hourly dictionary and daily dictionary which contains fields like temperature, humidity, etc etc
My main goal is to create a weather app using both of the dictionaries hourly and daily by loading them into a table view.
NSDictionary *hourlyDict = [dataFromWeb objectForKey:#"hourly"];
hourlyData = [hourlyDict objectForKey:#"data"];
NSDictionary *dailyDict = [dataFromWeb objectForKey:#"daily"];
dailyData = [dailyDict objectForKey:#"data"];
NSLog(#"%#", [[dailyData objectAtIndex:0] objectForKey:#"humidity"]);
}
By here i successfully created both the dictionaries and tried to NSlog the data it works fine.
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
I feel like my problem starts here in loading the dictionary into tableView.
1) In storyboard i embedded the table view into NavigationView.
2) i made the table View content as dynamic protocol
3) named the cell identifier as cell
i think problem starts here in sending data into table. Basically my app should contains 3 sections summary,hourly data and daily data. but i just want to try for now only on daily data.
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
Since i don't want any section, i removed this no.of. sections, but it threw me error, so kept it back and returned 0. , i also tried making it 1, but app crashes.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"hello");
return dailyData.count;
}
Here i want columns as no.of rows in dictionary, so i made dailyData.count.
Here starts the main problem, this - (UITableViewCell *)tableView:........ function is not being called, i tried to NSlog a message, it didn't show up
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
NSLog(#"hello");
cell.textLabel.text = [[dailyData objectAtIndex:indexPath.row]objectForKey:#"sunsetTime"];
return cell;
}
can some one help me out please. Thanks in advance. Im new to programming.
here i attached the Google Drive link for project
To fix your issue you need to set your number of sections to 1 (you must always have at least 1 section for anything to display).
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
The reason you are getting a crash when you set your number of sections to 1 is because you are trying to use an NSDictionary as an NSString. You need to get an NSString from the NSDictionary. The below code will get the summary from the daily data for that row and display the summary.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
NSDictionary *rowData = [dailyData objectAtIndex:indexPath.row];
cell.textLabel.text = [rowData objectForKey:#"summary"];
return cell;
}
// sections should be 1 instead of 0
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
[dailyData objectAtIndex:indexPath.row] has following dictionary that cannot be assigned as Cell label text , you have to assign some string value to Cell Label text
{
apparentTemperatureMax = "60.49";
apparentTemperatureMaxTime = 1462316400;
apparentTemperatureMin = "52.96";
apparentTemperatureMinTime = 1462276800;
cloudCover = "0.92";
dewPoint = "50.37";
humidity = "0.8100000000000001";
icon = "partly-cloudy-day";
moonPhase = "0.89";
ozone = "351.23";
precipIntensity = 0;
precipIntensityMax = 0;
precipProbability = 0;
pressure = "1014.68";
summary = "Mostly cloudy throughout the day.";
sunriseTime = 1462281126;
sunsetTime = 1462331002;
temperatureMax = "60.49";
temperatureMaxTime = 1462316400;
temperatureMin = "52.96";
temperatureMinTime = 1462276800;
time = 1462258800;
visibility = "8.779999999999999";
windBearing = 275;
windSpeed = "5.83";
}
cell.textLabel.text = [dailyData objectAtIndex:indexPath.row]; you are assigning a dictionary to tableViewCell label. if you want specific key value then check below code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
//Number to Sting --> [Number stringValue]
cell.textLabel.text = [[[dailyData objectAtIndex:indexPath.row]objectForKey:#"sunsetTime"] stringValue];
return cell;
}
I was trying to pass float into my table cell text, theres the mistake. We have to pass only text into that one, but i was trying to insert float values. now i passes some text values it works fine
Thank you all for your lovable support. Thank you once again
use this below code, And your code is working for me,
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"hello");
return dailyData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
NSLog(#"hello %#",[[dailyData objectAtIndex:indexPath.row] objectForKey:#"humidity"]);
cell.textLabel.text = [NSString stringWithFormat:#"%#",[[dailyData objectAtIndex:indexPath.row] objectForKey:#"humidity"]];
return cell;
}
And your output is given below,
humidity value is printed
hope its helpful
You must show not to come out the data, because your dailyData is a NSArray! How do you use an array as a string to use?Suggest you use a model, to store data.
NSDictionary *hourlyDict = [dataFromWeb objectForKey:#"hourly"];
hourlyData = [hourlyDict objectForKey:#"data"];
NSDictionary *dailyDict = [dataFromWeb objectForKey:#"daily"];
dailyData = [dailyDict objectForKey:#"data"];
for (id obj in hourlyData) {
newsModel *model=[[newsModel alloc]init ];
model.name=obj[#"summary"];
[_dataArray addObject:model];
}
NSLog(#"%#", [[dailyData objectAtIndex:0] objectForKey:#"humidity"]);
In the table view delegate :
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIde=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIde];
if (!cell) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIde ];
}
newsModel *model=_dataArray[indexPath.row];
cell.textLabel.text=model.name;
return cell;
}
I hope you guys help me in my code which is load data from a website. Let's start with the code:
-(void)viewDidLoad
{
[self loadDataFromUrl];
}
-(void)loadDataFromUrl {
NSString *myUrl = [NSString stringWithFormat:#"http://WebSite/PhpFiles/File.php"];
NSURL *blogURL = [NSURL URLWithString:myUrl];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization
JSONObjectWithData:jsonData options:0 error:&error];
for (NSDictionary *bpDictionary in dataDictionary) {
HotelObject *currenHotel = [[HotelObject alloc]initWithVTheIndex:
[bpDictionary objectForKey:#"TheIndex"] timeLineVideoUserName:
[bpDictionary objectForKey:#"timeLineVideoUserName"] timeLineVideoDetails:
[bpDictionary objectForKey:#"timeLineVideoDetails"] timeLineVideoDate:
[bpDictionary objectForKey:#"timeLineVideoDate"] timeLineVideoTime:
[bpDictionary objectForKey:#"timeLineVideoTime"] timeLineVideoLink:
[bpDictionary objectForKey:#"timeLineVideoLink"] timeLineVideoLikes:
[bpDictionary objectForKey:#"timeLineVideoLikes"] videoImage:
[bpDictionary objectForKey:#"videoImage"] timeDeviceToken:
[bpDictionary objectForKey:#"deviceToken"]];
[self.objectHolderArray addObject:currenHotel];
}
}
-(NSMutableArray *)objectHolderArray{
if(!_objectHolderArray) _objectHolderArray = [[NSMutableArray alloc]init];
return _objectHolderArray;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return [self.objectHolderArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
HotelObject *currentHotel = [self.objectHolderArray
objectAtIndex:indexPath.row];
cell.lblID.text = currentHotel.vvTheIndex;
cell.lblName.text = currentHotel.vvUserName;
cell.lblCity.text = currentHotel.vvVideoDate;
cell.lblAddress.text = currentHotel.vvVideoLikes;
return cell;
}
The above code is loading data from a Url and fill the TableView and this step working fine. The app has another ViewController which is DetailsView, in DetailsView users can update some info. When the user goes back to the TableView nothing happened (I mean the data still the same and not updated). I have tried to call the loadDataFromurl from ViewDidAppear but it does not work.
I did add:
[self.tableView reloadData];
But still the same result.
Her is also my NSObject code:
-(instancetype)initWithVTheIndex:(NSString *)vTheIndex
timeLineVideoUserName:(NSString *)vUserName
timeLineVideoDetails:(NSString *)vVideoDetails
timeLineVideoDate:(NSString *)vVideoDate
timeLineVideoTime:(NSString *)vVideoTime
timeLineVideoLink:(NSString *)vVideoLink
timeLineVideoLikes:(NSString *)vVideoLikes
videoImage:(NSString *)vVideoImage
timeDeviceToken:(NSString *)vDeviceToken {
self = [super init];
if(self){
self.vvTheIndex = vTheIndex;
self.vvUserName = vUserName;
self.vvVideoDetails = vVideoDetails;
self.vvVideoDate = vVideoDate;
self.vvVideoTime = vVideoTime;
self.vvVideoLink = vVideoLink;
self.vvVideoLikes = vVideoLikes;
self.vvVideoImage = vVideoImage;
self.vvDeviceToken = vDeviceToken;
}
return self;
}
My question is: How can I update the TableView when moving from DetailsView or even when I pull to refresh.
Thanks in advance
You are not properly reloading the data source of your UITableView.
Assuming the remote URL is getting updated with the new data, and the issue is only reloading the TableView, make sure you add your [self.tableView reloadData] AFTER loadDataFromUrl has finished.
The reloadData method will always refresh the table's content, so either it's not being called at the right time or you are not updating self.objectHolderArray. (You can debug that by setting a breakpoint after calling loadDataFromUrl after the update.)
on viewDidLoad lifecycle first [self.tableView reloadData] reload tableview then another work.
I have an requirement like the UITableview row height has to increase dynamically when i add more data..Like
_quoteArray = [#[#"For the past 33 years, I have looked in the mirror every morning and asked myself: 'If today were the last day of my life, would I want to do what I am about to do today?' And whenever the answer has been 'No' for too many days in a row, I know I need to change something. -Steve Jobs",
#"Be a yardstick of quality. Some people aren't used to an environment where excellence is expected. - Steve Jobs",
#"Innovation distinguishes between a leader and a follower. -Steve Jobs"]];
I wrote the code like…..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = #"NotificationCell";
MyNotificationCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
//cell.dateLabel.text =dateDisplayStr;
cell.teacherChangeLabel.text = _quoteArray[quoteIndex];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// Calculate a height based on a cell
static NSString *simpleTableIdentifier = #"NotificationCell";
MyNotificationCell *cell = [self.NotificationTableview dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if(!cell) {
cell = [self.NotificationTableview dequeueReusableCellWithIdentifier:#"CustomCell"];
}
// Configure the cell
int quoteIndex = indexPath.row % [quoteArray count];
cell.teacherChangeLabel.text = quoteArray[quoteIndex];
// Layout the cell
[cell setNeedsLayout];
// Get the height for the cell
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
// Padding of 1 point (cell separator)
CGFloat separatorHeight = 1;
return height + separatorHeight;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 140;
}
But it is not increasing the row height if I add extra data.I don’t know where I did mistake.Can anyone please help me in this
If you want to change based on the size of the string just do it like this:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *text = [yourStringArray objectAtIndex:indexPath.row];
UIFont *font = theFontSizeYourWant;
return [self heigthWithString:text andFont:font]+30//put the +30 for personal like;
}
- (CGFloat)heigthWithString:(NSString*)string andFont:(UIFont *)font
{
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:string];
[attrStr addAttribute:NSFontAttributeName
value:font
range:NSMakeRange(0, [attrStr length])];
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(250, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
context:nil];
return rect.size.height;
}
Hope this helps!
Use
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// Change the height of cell based on indexpath ForEg
if([indexPath row]==0){
return 44;
}
return 140;
}
to change the height of a cell.
If you need to support iOS7 and there are lots of items affecting the height.
As there are lots of items(or some dynamic size items), the height is not easy to calculate.
I would call a protocol method to update the height.
Pos:
Easy to change the height
No annoying calculation
Cons:
memory consumption
you may see the UITableView updating.
#property (strong, nonatomic) NSMutableArray *loadedCellHeight;
#pragma CellDelegate Methods
- (void)displayHeight:(NSString*)height atIndexPath:(NSIndexPath *)indexPath
{
NSPredicate *filter = [NSPredicate predicateWithFormat:#"indexPath == %#", indexPath];
NSArray *filteredArray = [self.loadedHeight filteredArrayUsingPredicate:filter];
if (filteredArray.count==0) {
[self.loadedAdHeight addObject:#{#"indexPath": indexPath, #"height": height}];
[self.tableView beginUpdates];
[self.tableView endUpdates];
} else {
NSDictionary *originalDict = filteredArray[0];
if ([[originalDict objectForKey:#"height"] floatValue] != [height floatValue]) {
[_loadedCellHeight removeObject:originalDict];
[_loadedCellHeight addObject:#{#"indexPath": indexPath, #"height": height}];
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dict = [self.dataArray objectAtIndex:indexPath.row];
NSPredicate *filter = [NSPredicate predicateWithFormat:#"indexPath == %#", indexPath];
NSArray *filteredArray = [self.loadedAdHeight filteredArrayUsingPredicate:filter];
if (filteredArray.count>0) {
return [filteredArray[0][#"height"] floatValue];
}
return 0;
}
What I did in my Cell(there is a webview inside it):
- (void)loadAd:(NSString*)path
{
if (_loaded) {
return;
}
NSString *encodeUrl = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
self.url = encodeUrl;
[self.webView setScalesPageToFit:YES];
self.webView.contentMode = UIViewContentModeScaleAspectFit;
self.webView.delegate = self;
self.webView.scrollView.bounces = NO;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:encodeUrl]];
[self.webView loadRequest:request];
}
-(void)parseHtml
{
NSString *html = [self.webView stringByEvaluatingJavaScriptFromString: #"document.body.innerHTML"];
NSLog(#"html:%#", html);
NSDictionary *dict = [NSDictionary dictionaryWithXMLString:html];
NSLog(#"parsed html:%#", [dict description]);
NSDictionary *heightDict = [dict dictionaryValueForKeyPath:#"img.hidden"];
NSLog(#"%#", [heightDict valueForKeyPath:#"_value"]);
NSString *heightStr = [heightDict valueForKeyPath:#"_value"];
NSString *height = [heightStr stringByReplacingOccurrencesOfString:#"advheight:" withString:#""] ;
if (self.delegate && !_loaded) {
[self.delegate displayHeight:height atIndexPath:_indexPath];
_loaded = YES;
}
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[self parseHtml];
}
When I load remote content via a block I update the UITableView by calling reloadData. However, I am unable to scroll on this data. I think this is because I have declared that the number of rows in the table is the length of my NSArray variable that will hold the contents of the list. When this is called though, the list has a count of zero. I would have assumed that by calling reloadData on the tableView that it would have recalculated the list size again.
Perhaps I'm missing a step along the way.
Thanks
Here is my code
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: #"MYURL"]];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
}
-(void) fetchedData:(NSData *)responseData
{
NSError* error;
id json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
self.dataList = json;
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self.tableView reloadData];
});
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.dataList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"SongCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
if([self.dataList count] > 0){
NSDictionary *chartItem = [self.dataList objectAtIndex:indexPath.row];
NSDictionary *song = [chartItem objectForKey:#"song"];
cell.textLabel.text = [song objectForKey:#"title"];
}
return cell;
}
Check that your json object (and therefore self.dataList) is not nil at the end of the asynchronous call. If it is, then [self.dataList count] will return 0.
Also, make sure that you correctly set self.dataList.dataSource.
This is working now.
The cause of the problem was the I had added a pan gesture to the UITableView
[self.view addGestureRecognizer:self.slidingViewController.panGesture];
This seems to interfere with the ability to scroll on a table. Hopefully this will help anyone who comes across this in the future.