Can't assign to the UILabel of custom cell of searchResultsTableView - ios

Everything works but can't assign value to the UILable of custom cell of searchResultsTableView. I am using the same custom UITableViewCell for my table view controller and it's searchDisplayController. I am using storyboard for the table view controller and table view cell. As you can see in the code, if I NSLog the value of self.searchResults[indexPath.row][#"name"], I can see the result in the console, but if I assign this value to cell.name.text, it won't work, but in the table view controller, it's working. The cell's imageView is working, I just can't assign any value to the cell's UILabel.
- (void)viewDidLoad
{
[super viewDidLoad];
[self.searchDisplayController.searchResultsTableView registerClass:[LocalCell class] forCellReuseIdentifier:#"Cell2"];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
static NSString *CellIdentifier2 = #"Cell2";
if (tableView == self.searchDisplayController.searchResultsTableView) {
LocalCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2 forIndexPath:indexPath];
if (!cell) {
cell = [[LocalCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2];
}
cell.name.text = self.searchResults[indexPath.row][#"name"];
NSLog(#"%#", self.searchResults[indexPath.row][#"name"]); // has value
NSLog(#"%#", cell.name.text); // null
return cell;
} else
{
LocalCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (!cell) {
cell = [[LocalCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.name.text = self.restaurants[indexPath.row][#"name"];
return cell;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 80;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
float radius = 1000.0f;
NSString *searchContent = [searchBar.text stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
if ([searchContent length] > 0) {
NSString *urlString = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=%f,%f&radius=%f&types=food&key=%#&sensor=true&name=%#", [[[NSUserDefaults standardUserDefaults] objectForKey:#"lat"] floatValue], [[[NSUserDefaults standardUserDefaults] objectForKey:#"lon"] floatValue], radius, AppKey, searchContent];
__weak LocalViewController *weakSelf = self;
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *taks = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
weakSelf.nextPageToken = dict[#"next_page_token"];
weakSelf.searchResults = dict[#"results"];
NSLog(#"search results: %#", weakSelf.searchResults);
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf.searchDisplayController.searchResultsTableView reloadData];
});
}
}];
[taks resume];
}
}
LocalCell.h
#import <UIKit/UIKit.h>
#interface LocalCell : UITableViewCell
#property (weak, nonatomic) IBOutlet UILabel *name;
#property (weak, nonatomic) IBOutlet UIImageView *imageView;
#property (weak, nonatomic) IBOutlet UILabel *desc;
#property (weak, nonatomic) IBOutlet UILabel *distance;
#end

I looked in your project:
NSLog(#"%#", cell.name.text); // null
Because cell.name is nil.
The explanation is: then you load your normal tableView, the cell "LocalCell" is loading from Storyboard, allocating and initialising your labels, but then you using self.searchDisplayController.searchResultsTableView you initialise "LoadCell", but never initialise his labels (because they are weak IBOutlets - and used in storyboard).
To solve your problem, I found 3 solutions:
1. Create another SearchCell with strong references to his UILabels, initialise all UILabel s in -(id)init of SearchCell. Then use it in your controller.
[self.searchDisplayController.searchResultsTableView registerClass:[SearchCell class] forCellReuseIdentifier:#"SearchCell"];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
static NSString *SearchCellIdentifier = #"SearchCell";
Restaurant *res;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
SearchCell *cell = [tableView dequeueReusableCellWithIdentifier:SearchCellIdentifier forIndexPath:indexPath];
if (!cell) {
cell = [[SearchCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
res = (Restaurant *)self.searchResults[indexPath.row];
cell.nameLabel.text = res.name;
cell.descLabel.text = res.desc;
// image load
return cell;
}
else
{
LocalCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (!cell) {
cell = [[LocalCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
res = (Restaurant *)self.restaurants[indexPath.row];
cell.nameLabel.text = res.name;
cell.descLabel.text = res.desc;
// image load
return cell;
}
}
Another way is to create a nib with your cell "SearchCellNib", and use your created LoadCell class. For load nib use:
cell = (LoadCell*)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = (LoadCell*)[[[NSBundle mainBundle] loadNibNamed:#"SearchCellNib" owner:nil options:nil] objectAtIndex:0];
}
Or use UITableViewCell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SearchCellIdentifier forIndexPath:indexPath];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
res = (Restaurant *)self.searchResults[indexPath.row];
cell.textLabel.text = res.name;
cell.detailTextLabel.text = res.desc;

Related

iOS: How to display parameters in response in tableview?

I am trying to set up a UITableView inside of a UIViewController. I am using storyboard. but when running it on the simulator, the tableview does not display any content. Here is what i tried in Xcode:
1) Drag a table view on UIView.
2) Connect it's outlets (dataSource and delegate).
3) I get response from server like:
[{"email_id":"adas#faga.gs","id":66,"mobile_no":"1236547895","name":"asad","relation":"dsfs"},{"email_id":"raj#ghj.com","id":67,"mobile_no":"5632145412","name":"raj","relation":"xyz"}]
4)Now what i want to do:
In 1st cell i want to display,
name:asad mobile:1236547895 email:adas#faga.gs relation:dsfs
and in 2nd cell,
name:raj mobile:5632145412 email:raj#ghj.com relation:xyz
But i have no idea about how to do this.Please anyone can solve my issue. help will be appreciable.
I do like following way but it's not working.
a) Add a new file to the project, with the Objective-C class template. Name it EmergencyContactCell and make it a subclass of UITableViewCell.
b) then in EmergencyContactCell.h
#interface EmergencyContactCell : UITableViewCell
#property (nonatomic, weak) IBOutlet UILabel *name;
#property (nonatomic, weak) IBOutlet UILabel *email;
#property (nonatomic, weak) IBOutlet UILabel *mobile;
#property (nonatomic, weak) IBOutlet UILabel *relation;
c) then MainStoryboard.storyboard, select the prototypecell and in the Identity Inspector change its class to EmergencyContactCell
d) Then connect all outlets
e) I am using AFNetworking to take response from server, when i got response, after that i do like following way:
NSArray *ResponseArray = [NSJSONSerialization JSONObjectWithData: responseObject options: kNilOptions error: nil];
if (ResponseArray.count >0)
{
menuItems = [ResponseArray mutableCopy];
[yourTableviewname reloadData];
}
f) and for display it on cell,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [menuItems count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"EmergencyContactCell";
//static NSString *simpleTableIdentifier = #"cell";
EmergencyContactCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
// NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
// cell.textLabel.text = [NSString stringWithFormat:#"Name:%#, Mobile:%#, Email:%#, Relation:%#",content[#"name"],content[#"mobile_no"],content[#"email_id"],content[#"relation"]];
//
return cell;
}
I'm not getting what to do at last??
Step-1
No need of this
NSArray *ResponseArray = [NSJSONSerialization JSONObjectWithData: responseObject options: kNilOptions error: nil];
NSMutableArray *finalArray = [NSMutableArray array];
for (NSDictionary *temp in ResponseArray) {
[finalArray addObject:temp[#"name"]];
}
NSLog(#"%#",finalArray);
if(finalArray != nil && finalArray.count > 0){
menuItems=[NSArray arrayWithArray:finalArray];
NSLog(#"menu items: %#",menuItems);
}
else{
NSLog(#"zero values from server");
}
Simply Do like
NSArray *ResponseArray = [NSJSONSerialization JSONObjectWithData: responseObject options: kNilOptions error: nil];
if (ResponseArray.count >0)
{
menuItems = [ResponseArray mutableCopy];
[yourTableviewname reloadData];
}
Step-2
for your answer continution
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"Name:%#, Mobile:%#, Email:%#, Relation:%#",content[#"name"],content[#"mobile_no"],content[#"email_id"],content[#"relation"]];
return cell;
}
Updated Answer
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"EmergencyContactCell";
EmergencyContactCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSDictionary *content = [menuItems objectAtIndex:indexPath.row];
cell.name.text = [NSString StringWithFormat:#"Name:%#",content[#"name"]];
cell.email.text = [NSString StringWithFormat:#"email:%#",content[#"email"]];
cell.mobile.text = [NSString StringWithFormat:#"mobile:%#",content[#"mobile"]];
cell.relation.text = [NSString StringWithFormat:#"relation:%#",content[#"relation"]];
return cell;
}
You need to do 2 things
After getting response set that into one NSArray. Declare NSArray
global one. And your code should be like
NSArray *arrayPersonalInfo = responseObject; // responseObject is response
got from server. Then call [tableView reloadData];
Now update your table view methods to
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return arrayPersonalInfo.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
NSDictionary *dictionaryMenu = [arrayPersonalInfo objectAtIndex:indexPath.row]; // It will save dictionary object of index
cell.textLabel.text = [NSString stringWithFormat:#"Name:%# Mobile:%# Email:%# Relation:%#",[dictionaryMenu valueForKey:#"name"],[dictionaryMenu valueForKey:#"mobile_no"],[dictionaryMenu valueForKey:#"email_id"],[dictionaryMenu valueForKey:#"relation"]];
cell.textLabel.numberOfLines = 0;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
return cell;
}
If needed add other table view methods like
heightForRowAtIndexPath and numberOfSections
If you prefer using storyboard, you can actually add a label into a prototype cell, make sure you set the prototype's cellIdentifier correctly to use it in codes. Then set a unique tag to your label. From your codes you can call viewWithTag from your cell's contentView to get the label and edit it's text property.

UItableView deplicated cell when scrolling

Sorry for posting this question again but I've looked into many answers and neither of them was helpfull to solve my issue.
So this my code :
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifier = #"radioCell";
RadioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[RadioTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
}
[self configureCommentCell:cell atIndexPath:indexPath];
return cell;
}
when I scroll down my cell get mixed up and some of data are repeated, so I've tried this :
static NSString *CellIdentifier = #"memberCell";
RadioCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[RadioTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
and this :
RadioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[RadioTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
}
But it didn't fixed my issue and I get white empty cells ? please how to fix this issue ?
Update
- (void)configureCommentCell:(RadioTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
NSDictionary *object;
if ([_dataArray[indexPath.section] isKindOfClass:[NSArray class]])
object = [_dataArray[indexPath.section] objectAtIndex:indexPath.row];
else
object = [[_dataArray[indexPath.section] valueForKey:#"radioList"] objectAtIndex:indexPath.row];
if (object[#"jsonUrl"]) {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:object[#"jsonUrl"] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//NSDictionary *tempObject = (NSDictionary *) responseObject;
if (![[responseObject objectForKey:#"type"] isEqualToString:#"error"]) {
NSDictionary *tempObject = [responseObject[#"data"] objectAtIndex:0];
cell.playingNow.text = tempObject[#"song"];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
cell.name.text = [NSString stringWithFormat:#" %#", object[#"title"]];
if (object[#"logoUrl"])
[cell.logo setImageWithURL:[NSURL URLWithString:object[#"logoUrl"]]];
}
I see that your problem is that you are fetching the data of you cells inside configureCommentCell that's called inside cellForRowAtIndexPath. which is wrong, because it too late to fetch data inside cellForRowAtIndexPath, in this delegate method you should return the cell.
this line may be called before retrieving the data from server :
cell.name.text = [NSString stringWithFormat:#" %#", object[#"title"]];
Instead you should:
Fetch the data inside a separate method for example fetchData
when the data is downloaded inside the completion block of AFNetworking method, store the data inside an NSArray called for example myDataArray still inside the completion block call [self.tableView reloadData];
In viewDidLoad method just call your method fetchData
And your cellForRowAtIndexPath should looks like this:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// hey please give me the cell to display ... harry up please
// please harry up ! oh my god you are fetching data from server
// while I am asking for the cell !
// ok I don't care do what you want
// I will return an empty cell anyway
// and guess what I will not take in consideration
// the retried data because it's inside a block
// which is called asynchronously
static NSString *cellIdentifier = #"radioCell";
RadioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) {
cell = [[RadioTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier]; }
// now before return the cell you need to update the content of cell
// maybe you have an array of items and you should update the label
// for example here and then return the cell
cell.usernameLabel = self.myDataArray[indexPath.row]; // example
return cell;
}
Well the TableView is reusing the cells, and you add the image every time a cell is displaid. Thus when reusing the cell you add an other image, but there already is an image.
You will have to reuse the image view, and only add the image if you create the cell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifer = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer]autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20,0,30,44)];
imageView.tag = 1001;
[cell addSubview:imageView];
[imageView release], imageView= nil;
}
TabBarTestAppDelegate *delegate = (TabBarTestAppDelegate *)[[UIApplication sharedApplication] delegate];
NSArray *local = delegate.myData;
// ok, it's horrible, don't look at it :-)
cell.textLabel.text = [NSString stringWithFormat:#"%#%#", #" " ,[local objectAtIndex:indexPath.row]];
//
NSString* name = nil;;
if (indexPath.row == 0) {
name = #"topicon";
}
else if (indexPath.row + 1 == [local count]) {
name = #"bottomicon";
}
else {
name = #"innericon";
}
UIImageView *imageView = (UIImageView *)[cell viewWithTag:1001];
imageView.image = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:name ofType:#"png"]];
return cell;
}

UITableView inside UIView - data loads only when scrolling cells outside uitableview

I have a problem using a UITableView inside a UIViewController:
When I start the app the UITableView is shown, but the data from _opponents isn't shown.
When I start scrolling the first cell outside the UITableView, now this cell gets updated.
Also, when I trigger [_topponents reloaddata] manually, the whole UITableView shows the correct data.
What do I have to add or change, so that the data is shown from the beginning?
dataSource and delegate are both connected with the class in the storyboard
Here is my code:
viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
myappdel = (AppDelegate *)[UIApplication sharedApplication].delegate;
self.title = #"New Match";
_lopponent.text = _opponent;
opponents = [[NSMutableArray alloc] init];
NSMutableDictionary *opponent = [[NSMutableDictionary alloc] init];
[opponent setObject:#"opponent A" forKey:#"name"];
[opponent setObject:#"xx matches | xx wins || xx losts" forKey:#"stats"];
[opponent setObject:#"Krems" forKey:#"location"];
NSMutableDictionary *opponent2 = [[NSMutableDictionary alloc] init];
[opponent2 setObject:#"opponent B" forKey:#"name"];
[opponent2 setObject:#"yy matches | yy wins || yy losts" forKey:#"stats"];
[opponent2 setObject:#"Location B" forKey:#"location"];
NSMutableDictionary *opponent3 = [[NSMutableDictionary alloc] init];
[opponent3 setObject:#"opponent C" forKey:#"name"];
[opponent3 setObject:#"zz matches | zz wins || zz losts" forKey:#"stats"];
[opponent3 setObject:#"Location C" forKey:#"location"];
[opponents addObject:opponent];
[opponents addObject:opponent2];
[opponents addObject:opponent3];
[_topponents reloadData];
}
and here my cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"opponentcell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *lopponentname = (UILabel*)[cell viewWithTag:1];
UILabel *lopponentstats = (UILabel*)[cell viewWithTag:2];
UILabel *llocation = (UILabel*)[cell viewWithTag:3];
lopponentname.text = [[opponents objectAtIndex:indexPath.row] objectForKey:#"name"];
lopponentstats.text = [[opponents objectAtIndex:indexPath.row] objectForKey:#"stats"];
llocation.text = [[opponents objectAtIndex:indexPath.row] objectForKey:#"location"];
return cell;
}
I found my fault!
I used to write:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]
but I should use
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
with "forIndexPath"
I think, the trouble is in the cell. Create UITableViewCell subclass.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"opponentcell";
CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.lopponentname.text = [[opponents objectAtIndex:indexPath.row] objectForKey:#"name"];
cell.lopponentstats.text = [[opponents objectAtIndex:indexPath.row] objectForKey:#"stats"];
cell.llocation.text = [[opponents objectAtIndex:indexPath.row] objectForKey:#"location"];
return cell;
}
Hope it helps you.
Add this after initialisation of cell. For me works properly.
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
I think you are using custom cel and it looks you have trouble in "cellForRowAtIndexPath". If you using .xib, you may find it useful.
static NSString *cellIdentifier = #"opponentcell";
CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
NSArray *nibObjects =[[NSBundle mainBundle] loadNibNamed:#"CustomTableViewCell" owner:nil options:nil];
for (id currentObject in nibObjects)
{
if ([currentObject isKindOfClass:[CustomTableViewCell class]])
{
cell = (CustomTableViewCell *) currentObject;
}
}
[cell initViewStyles];
}
You need to check for condition when cell is nil..
Initially the cell is nil..
So the data is loading only after scrolling...
Add below lines of code in your cellForRowAtIndexPath delegate method after initializing cell.
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Hope this fixes the issue...

iOS : reloadData not working

I'm new to the whole iOS developement, so not really good at it. I currently have a viewController with two tableviews. The first table is always visible and contains categories. The second table should only be visible when a cell from the first table is selected. The second table then contains subitems from the cell that was selected in the first tableview. Both tableviews are connected to their property in the .h file.
The viewcontroller itself is connected to a FoodAddViewController.h and FoodAddViewController.m file.
In the FoodAddViewController.h file, I have:
#import <UIKit/UIKit.h>
#class FoodAddViewController;
#interface FoodAddViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UITableView *Categorien;
#property (strong, nonatomic) IBOutlet UITableView *Invulling;
- (IBAction)cancel:(id)sender;
#end
For the FoodAddViewController.m, I have:
#interface FoodAddViewController ()
{
NSArray *CategoryLabel;
NSMutableArray *elementen;
}
#end
#implementation FoodAddViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.Categorien.layer.transform = CATransform3DRotate(CATransform3DIdentity,-1.57079633,0,0,1);
self.Categorien.frame=CGRectMake(0,200, 700,234);
[self.Invulling setHidden:TRUE];
self.Invulling.layer.transform = CATransform3DRotate(CATransform3DIdentity,-1.57079633,0,0,1);
self.Invulling.frame=CGRectMake(0,200, 700,234);
self.Categorien.dataSource = self;
self.Categorien.delegate = self;
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"categorie" ofType:#"txt"];
NSString *content = [NSString stringWithContentsOfFile:filePath
encoding:NSMacOSRomanStringEncoding
error:NULL];
NSArray * categories = [content componentsSeparatedByString:#"\n"];
CategoryLabel = categories;
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(self.Categorien==tableView) {
return CategoryLabel.count;
}
if(self.Invulling==tableView) {
return elementen.count;
}
return 0;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(self.Categorien==tableView) {
static NSString *CellIdentifier = #"Cell";
CustomCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!Cell) {
Cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.layer.transform = CATransform3DRotate(CATransform3DIdentity,1.57079633,0,0,1);
Cell.frame=CGRectMake(0,0,234,150);
Cell.textLabel.text = [CategoryLabel objectAtIndex:indexPath.row];
return Cell;
}
if(self.Invulling==tableView) {
static NSString *CellIdentifier = #"DetailCell";
CustomCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!Cell) {
Cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.layer.transform = CATransform3DRotate(CATransform3DIdentity,1.57079633,0,0,1);
Cell.frame=CGRectMake(0,0,234,150);
Cell.textLabel.text = [elementen objectAtIndex:indexPath.row];
return Cell;
}
return NULL;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 200;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.Invulling.dataSource = self;
self.Invulling.delegate = self;
elementen = [[NSMutableArray alloc]init];
if(self.Categorien==tableView) {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
PFQuery *query = [PFQuery queryWithClassName:cellText];
[query selectKeys:#[#"Naam"]];
NSArray *result = [query findObjects];
for (PFObject *object in result) {
NSString *naam = object[#"Naam"];
if(![elementen containsObject:naam]) {
[elementen addObject:naam];
}
}
}
[self.Invulling setHidden:FALSE];
[self.Invulling reloadData];
}
end
Now, the problem is that the reloadData method does not work correctly. For example: if I press the first cell from the first tableview (Categorien), then nothing happens. But when I click another cell, the second tableview (Invulling) gets loaded with the results from the first cell.
you have to use didSelectRowAtIndexPath not didDeselectRowAtIndexPath method
Also look up some tutorial on debugging, you could have known that the method is not
being called if you have added breakpoints
You are using
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:
Instead, use
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:

How to set tableView cell title in ios?

I am parsing JSON and storing it in an array.I have a custom cell subclass in which I am trying to set the title of a label from the content of parsed JSON.
This is the parsing process.
#implementation BlogScreenViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.jsonArray = [[NSMutableArray alloc]init];
NSError *error = nil;
NSURL *url = [NSURL URLWithString:#"http:web_services/blog.php"];
NSData *data = [NSData dataWithContentsOfURL:url];
self.jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
for (NSDictionary *obj in self.jsonArray)
{
NSLog(#"JSON string output :- %# ", [obj objectForKey:#"titre"]); // shows titles
}
In custom cell subclass
// set blog title label
UILabel *blogTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 20, 200, 20)];
// blogTitleLabel.text = #"This is blog title"; // This shows properly if used.
for (NSDictionary *obj in blogScreenVC.jsonArray ) //This doesn't work.
{
blogTitleLabel.text = [NSString stringWithFormat:#"%#",[obj objectForKey:#"titre"]];
}
[blogTitleLabel setFont:[UIFont systemFontOfSize:9]];
[self addSubview:blogTitleLabel];
Instead of Setting lebel.text in customcell class add it in the cellForRowAtIndexPath.
Create Property of label in customcell.h file
#property (nonatomic, weak) IBOutlet UILabel *label;
And in customcell.m file synthesys it.
#synthesize label = _label;
And in you viewcontroller.m file
#import "CustomCell.h"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (self.jsonArray.count !=0) {
NSMutableDictionary * tmpDictn = [self.jsonArray objectAtIndex:indexPath.row];
if ([tmpDictn objectForKey:#"titre"] != nil)
{
cell.label.text = [tmpDictn objectForKey:#"titre"];
}else{
cell.label.text = #"tmpDictn does not contain data";
}
}else{
cell.label.text = #"jsonArray does not contain data";
}
return cell;
}

Resources