im newbie IOS and using IB, im working UITableView in UIViewController, i have implement "UITableViewDelegate, UITableViewDataSource" in viewcontroller and setdelegate,datasource for uitableview but it dosen't work, i dont know,
please help me!
thank for your read this article.
code viewcontroller.h
#interface ViewController : UIViewController<UITableViewDelegate,
UITableViewDataSource> #property (nonatomic, retain) IBOutlet UITableView *tableView;
code viewcontroller.m
- (void)viewDidLoad { [tableView setDataSource:self];
[tableView setDelegate:self];
dispatch_async(htvque, ^{
NSData* data = [NSData dataWithContentsOfURL: listFilmByCate];
NSError* error;
jsonTable = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
listDataTable = [jsonTable objectForKey:#"List"];
dispatch_async(dispatch_get_main_queue(), ^{
[tableView reloadData];
});
});
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return listDataTable.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dataTable = [listDataTable objectAtIndex:indexPath.row];
NSData *receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[dataTable objectForKey:#"Thumbnail"]objectForKey:#"Url1"]]]; UIImage *image = [[[UIImage alloc] initWithData:receivedData] stretchableImageWithLeftCapWidth:50 topCapHeight:80];
static NSString *simple_cell = #"simpleCell";
CustomizeCell_Home *customize_cell = (CustomizeCell_Home *)[tableView dequeueReusableCellWithIdentifier:simple_cell];
if (simple_cell == nil)
{}
customize_cell.imageView.image = image;
customize_cell.lbldescription.text =[dataTable objectForKey:#"LongDescription"];
customize_cell.lblTitle.text = [dataTable objectForKey:#"VName"];
customize_cell.lblTitle.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.numberOfLines=4;
customize_cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bgtblRight.png"]];
return customize_cell;
}
in this line of code is your problem:
CustomizeCell_Home *customize_cell = (CustomizeCell_Home *)[tableView dequeueReusableCellWithIdentifier:simple_cell];
if (simple_cell == nil)
{}
what would happens if customize_cell is nil?
you are not instanciating the customize_cell and because of that you cant call these methods:
customize_cell.imageView.image = image;
customize_cell.lbldescription.text =[dataTable objectForKey:#"LongDescription"];
customize_cell.lblTitle.text = [dataTable objectForKey:#"VName"];
customize_cell.lblTitle.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.numberOfLines=4;
customize_cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bgtblRight.png"]];
return customize_cell;
just add a simple inicialize cell inside the if, like this:
if (customize_cell == nil)
{
customize_cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"AnIdentifierString"] autorelease];
}
EDIT
change this:
CustomizeCell_Home *customize_cell = (CustomizeCell_Home *)[tableView dequeueReusableCellWithIdentifier:simple_cell];
if (simple_cell == nil)
{}
customize_cell.lbldescription.text =[dataTable objectForKey:#"LongDescription"];
customize_cell.lblTitle.text = [dataTable objectForKey:#"VName"];
customize_cell.lblTitle.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.numberOfLines=4;
customize_cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bgtblRight.png"]];
return customize_cell;
to:
CustomizeCell_Home *customize_cell = (CustomizeCell_Home *)[tableView dequeueReusableCellWithIdentifier:simple_cell];
if (customize_cell == nil)
{
customize_cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"AnIdentifierString"] autorelease];
}
customize_cell.lbldescription.text =[dataTable objectForKey:#"LongDescription"];
customize_cell.lblTitle.text = [dataTable objectForKey:#"VName"];
customize_cell.lblTitle.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.numberOfLines=4;
customize_cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bgtblRight.png"]];
return customize_cell;
Set,
tableView. dataSource = self;
tableView. delegate = self;
Implement protocol which are directed as #required means to say mandatory
-(UITableViewCell*) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
// dint concentrate on this part, hope u are right
NSDictionary *dataTable = [listDataTable objectAtIndex:indexPath.row];
NSData *receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[dataTable objectForKey:#"Thumbnail"]objectForKey:#"Url1"]]];
UIImage *image = [[[UIImage alloc] initWithData:receivedData] stretchableImageWithLeftCapWidth:50 topCapHeight:80];
static NSString *simple_cell = #"simpleCell";
// works like double ended queue.... cells are re-used when available... so when cell is nil, u need to create
CustomizeCell_Home *customize_cell = (CustomizeCell_Home *)[tableView dequeueReusableCellWithIdentifier:simple_cell];
if (simple_cell == nil)
{
// CustomizeCell_Home is linked to CustomizeCell_Home_Reference using nib,
[[NSBundle mainBundle] loadNibNamed: #"CustomizeCell_Home" owner: self options: nil];
customize_cell = CustomizeCell_Home_Reference;
}
.....
.....
return customize_cell;
}
First thing, the cells are never allocated, instead of doing if(simple_cell==nil), you should do if(customize_cell==nil) and do the initialization code there. Otherwise you're comparing a string that you just created and set a value to against nil.
Related
There is many library available for this case, but my scenario is a bit different. I have a ViewController having three textfields. I have to implement autocomplete for every textfields, and show the suggestion below the textfield. For all the datasource of textfield,I am dependent on the web-service. The problem is its working only for one textfield. Please suggest some effecient way to do this.
1)Suggestions should be shown below or above the textfield, after entering two characters. UI shouldn't be blocked, user can continue typing.(I am making call on the server with two character on background thread, and receive the response to show as suggestions. Filter logic is implemented on the server)
2) If user doesn't select anything from the suggestion, textfield data will be send to the server.
3) Anywhere tap on the screen should hide the suggestion.(The problem is, if I use tap gesture recognizer, tableview cell also doesn't get touch)
creating tableview to show suggestions
- (void)viewDidLoad {
[super viewDidLoad];
self.orderNoTextField.delegate = self;
self.empNameTextField.delegate = self;
self.custNameTextField.delegate = self;
rectForEmp = CGRectMake(0, self.empNameTextField.frame.origin.y + self.empNameTextField.frame.size.height, self.empNameTextField.frame.size.width, 120);
rectForCust = CGRectMake(0, self.orderNoTextField.frame.origin.y, self.custNameTextField.frame.size.width, 120);
autocompleteTableView = [[UITableView alloc] initWithFrame:rectForCust style:UITableViewStylePlain];
autocompleteTableView.backgroundColor = [UIColor clearColor];
autocompleteTableView.delegate = self;
autocompleteTableView.dataSource = self;
autocompleteTableView.scrollEnabled = YES;
autocompleteTableView.hidden = YES;
autocompleteTableView.canCancelContentTouches = NO;
autocompEmpTableView = [[UITableView alloc] initWithFrame:rectForEmp style:UITableViewStylePlain];
autocompEmpTableView.backgroundColor = [UIColor clearColor];
autocompEmpTableView.delegate = self;
autocompEmpTableView.dataSource = self;
autocompEmpTableView.scrollEnabled = YES;
autocompEmpTableView.hidden = YES;
autocompEmpTableView.canCancelContentTouches = NO;
[self.view addSubview:autocompleteTableView];
[self.view addSubview:autocompEmpTableView];
}
fetching suggestions
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (self.custNameTextField.text.length == 2)
{
autocompEmpTableView.hidden = YES;
[self generateDataForCustomerName];
}
else if (self.empNameTextField.text.length == 2)
{
autocompleteTableView.hidden = YES;
[self generateDataForEmployeeName];
}
return YES;
}
- (void)generateDataForCustomerName
{
/** get background thread for datasource of autocomplete **/
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
{
httpClient = [[KKHttpClient alloc]init];
//httpClient.responseDelegate = self;
//NSString *params = [self.empNameTextField text];
params = [NSString stringWithFormat:#"{\"rqBody\":{\"searchKey\":\"%#\"}}",[self.custNameTextField text]];
relativeUrl = [NSString stringWithFormat:#"auth/getcustomernamelist"];
[httpClient connectWithUrl:relativeUrl withData:params completion:^(NSMutableDictionary *responseJson)
{
NSLog(#"response check for new methods:%#", responseJson);
dispatch_async(dispatch_get_main_queue(), ^{
//Here returns to main thread to update the UI.
/** initialize the array and add object to it**/
custNameData = [[NSMutableArray alloc]init];
custNameData = [responseJson[#"rsBody"]valueForKey:#"msg"];
autocompleteTableView.hidden = NO;
[autocompleteTableView reloadData];
});
}];
}
});
}
Tableview to show suggesyions
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section {
if(tableView == autocompleteTableView)
{
return empNameData.count;
}
else
{
return custNameData.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView == autocompEmpTableView) {
UITableViewCell *cell = nil;
static NSString *AutoCompleteRowIdentifier = #"AutoCompEmpRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier];
}
employeeName = [[empNameData valueForKey:#"employeeName"]objectAtIndex:indexPath.row];
employeeId = [[empNameData valueForKey:#"employeeId"]objectAtIndex:indexPath.row];
NSString *autoCompleteText = [NSString stringWithFormat:#"%# %#%#%#", employeeName, #"(", employeeId, #")"];
cell.textLabel.text = autoCompleteText;
return cell;
}
else
{
UITableViewCell *cell = nil;
static NSString *AutoCompleteRowIdentifier = #"AutoCompleteRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier];
}
customerName = [[custNameData valueForKey:#"customerName"]objectAtIndex:indexPath.row];
customerCode = [[custNameData valueForKey:#"customerCode"]objectAtIndex:indexPath.row];
NSString *autoCompleteText = [NSString stringWithFormat:#"%# %# %#%#", customerName, #"(", customerCode, #")"];
cell.textLabel.text = autoCompleteText;
return cell;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *title = selectedCell.textLabel.text;
if(tableView == autocompEmpTableView)
{
self.empNameTextField.text = title;
autocompEmpTableView.hidden = YES;
}
else{
self.custNameTextField.text = title;
autocompleteTableView.hidden =YES;
}
}
I have two UIViewControllers with tableview. When the first cell loads in the second UIViewController it calls the cellForRowAtIndexPath in the same class but when it loads the second cell it calls the first viewControllers cellForRowAtIndexPath.
My code as follows:
SecondViewController:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NotificationsTableViewCell *cell = [self.notificationsTableView dequeueReusableCellWithIdentifier:#"NotificationCell"];
if(cell == nil)
{
cell = [[NotificationsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"NotificationCell"];
}
NSMutableDictionary *cellData = [self.databaseCall transactionFromDatabase:indexPath.row];
NSLog(#"%#", cellData);
cell.goalNameLabel.text = [cellData objectForKey:#"categoryName"];
NSString *cardTypeId = [cellData objectForKey:#"cardTypeId"];
NSString *tipsId = [cellData objectForKey:#"tipsId"];
if([self.defaultCardTypeId containsObject:cardTypeId])
{
NSUInteger index = [self.defaultCardTypeId indexOfObject:cardTypeId];
[self.defaultCardTypeId replaceObjectAtIndex:index withObject:cardTypeId];
}
else{
[self.defaultCardTypeId addObject:cardTypeId];
}
if([self.defaultTipId containsObject:tipsId])
{
NSUInteger index = [self.defaultCardTypeId indexOfObject:cardTypeId];
[self.defaultTipId replaceObjectAtIndex:index withObject:cardTypeId];
}
else{
[self.defaultTipId addObject:tipsId];
}
if([cardTypeId isEqualToString:#"1"])
{
UIImage *cellImage = [UIImage imageNamed:#"icon2.jpg"];
cell.cardTypeImage.image = cellImage;
cell.cardTypeLabel.text = #"GOOD TO KNOW";
cell.cardTypeLabel.textColor = [UIColor colorWithRed:252/255.0 green:171/255.0 blue:19/255.0 alpha:1];
}
if([cardTypeId isEqualToString:#"2"])
{
UIImage *cellImage = [UIImage imageNamed:#"icon1.jpg"];
cell.cardTypeImage.image = cellImage;
cell.cardTypeLabel.text = #"TO CONSIDER";
cell.cardTypeLabel.textColor = [UIColor colorWithRed:0/255.0 green:191/255.0 blue:243/255.0 alpha:1];
}
cell.notificationCard.layer.cornerRadius = 5;
// Configure the cell...
return cell;
}
FirstViewController:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
GoalsCustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"GoalsListCell" forIndexPath:indexPath];
if(cell == nil)
{
cell = [[GoalsCustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"GoalsListCell"];
}
NSInteger indexOfCategory = [self.databaseCall.arrColumnName indexOfObject:#"CategoryName"];
NSInteger indexOfImage = [self.databaseCall.arrColumnName indexOfObject:#"CategoryImage"];
NSInteger indexOfActive = [self.databaseCall.arrColumnName indexOfObject:#"coulmn"];
//Assigning the contents of cell
cell.goalName.text = [NSString stringWithFormat:#"%#", [[self.arrCategoryTitle objectAtIndex:indexPath.row] objectAtIndex:indexOfCategory]];
NSString *categoryImage = [NSString stringWithFormat:#"%#", [[self.arrCategoryTitle objectAtIndex:indexPath.row] objectAtIndex:indexOfImage]];
NSString *activeStatus = [NSString stringWithFormat:#"%#", [[self.arrCategoryTitle objectAtIndex:indexPath.row] objectAtIndex:indexOfActive]];
UIImage *cellImage = [UIImage imageNamed:categoryImage];
cell.goalImage.image = cellImage;
[cell.favouriteButton addTarget:self action:#selector(favouriteButtonPressed:) forControlEvents:UIControlEventTouchDown];
NSMutableString *selectedRowImage = [[NSMutableString alloc] initWithString:#""];
//Checking whether the category is selected by user or not
if([activeStatus isEqualToString:#"yes"])
{
selectedRowImage = [NSMutableString stringWithFormat:#"starsel.png"];
}
else
{
selectedRowImage = [NSMutableString stringWithFormat:#"stardef.png"];
}
UIImage *favouriteIconImage = [UIImage imageNamed:selectedRowImage];
[cell.favouriteButton setBackgroundImage:favouriteIconImage forState:UIControlStateNormal];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Configure the cell...
return cell;
}
Thanks in advance.
First of all i would say sorry for this stupid question.
The problem is due to the tableview datasource as specifies by #Paulw11, #Onik IV, #Kannan Vora. The secondViewController tableView has the datasource of firstViewController.
at the Moment i have the following classes:
My Problem is that my Custom Cell Class "GTNewsCustomCell" is never called, i set some breakpoints in the .m file but nothing happend, than i realized that in my "cellForRowAtIndexPath" the cell is never nil!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier1 = #"NewsCell";
GTNewsCustomCell *newsCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if(newsCell == nil){
newsCell = [[GTNewsCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1];
}
newsCell.titleLabel.text = [[self.newsList objectAtIndex:indexPath.section]objectForKey:#"title"];
NSAttributedString *attString = [[NSAttributedString alloc]initWithString:[[self.newsList objectAtIndex:indexPath.section]objectForKey:#"previewMessage"]];
newsCell.messageTextView.attributedText = attString;
return newsCell;
}
And here is a little part of my Code from my GTNewsCustomCell.m:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
self.messageTextView.textColor = [UIColor blackColor];
self.messageTextView.backgroundColor = GTDefaultTextBackgroundColor;
self.messageTextView.editable = NO;
self.messageTextView.userInteractionEnabled = NO;
self.messageTextView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
NSString *htmlTag = #"<b></b>";
NSString *html = [NSString stringWithFormat:#"%#%#",htmlTag,self.messageTextView.attributedText];
NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
CGFloat fontSizeMultiplier = 1.1;
CGFloat const DTCoreTextDefaultFontSize = 12.0;
NSString * fontName = #"Helvetica";
DTCSSStylesheet* css;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"7.0")){
css = [[DTCSSStylesheet alloc] initWithStyleBlock:#"ul li{padding-left: -10px;}"];
NSMutableDictionary *options = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:fontSizeMultiplier], NSTextSizeMultiplierDocumentOption,
fontName, DTDefaultFontFamily,
#"purple", DTDefaultLinkColor,
#"red", DTDefaultLinkHighlightColor,
css,DTDefaultStyleSheet,
[NSNumber numberWithBool:YES],DTUseiOS6Attributes,
nil];
.
.
.
.
Here are some screenshots from my xib Files for more information:
My GTNewsTableViewController:
GTNewsCustomCell (FilesOwner):
GTNewsCustomCell (View):
GTNewsCustomCell:
Okay, since you're doing the registration of cells via tableView's method registerNib:forCellReuseIdentifier:. The initWithStyle:reuseIdentifier: won't ever get called. If you'd like to do the styling, use -awakeFromNib method of your UITableViewCell subclass.
- (void)awakeFromNib {
[super awakeFromNib];
self.messageTextView.textColor = [UIColor blackColor];
self.messageTextView.backgroundColor = GTDefaultTextBackgroundColor;
self.messageTextView.editable = NO;
self.messageTextView.userInteractionEnabled = NO;
}
with GTNewsCustomCell (FilesOwner), you will not be able to reuse this cell if needed. you should make it NSObject(FileOwner). and load this cell in cellForRowAtIndexPath.
by this way , you will get the same style of of your custom cell.
static NSString *CellIdentifier= #"CustomCell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:#"CustomCell"
owner:self//transfer ownership to self
options:nil];
cell = [nibViews objectAtIndex:0];
}
return cell;
}
I have a simple iOS app which parses multiple JSON feeds and stores the data in multiple strings. I know exactly which strings to use for what and how long the count is because the JSON feeds are feeds that I control from some of my websites.
However, even though I have specified this in the "tableView cellForRowAtIndexPath" method, the UITableView still won't populate..
Is this because I am using strings to populate the UITableView? And if so, do you HAVE to use arrays to populate a UITableView.
Thanks for you're time :)
UPDATE: Here is m code:
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 5;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Printing table view.");
static NSString *CellIdentifier = #"Cell";
AccountCell *cell = (AccountCell *)[account_table dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AccountCell" owner:self options:nil];
cell = [nib objectAtIndex: 0];
// Draws the cell background.
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"uiFeedletsnglass5.png"]];
// Draws the pressed cell background.
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"cell-on.png"]];
// Round of edges of content view in Carousel.
cell.layer.cornerRadius = 5;
cell.layer.masksToBounds = YES;
cell.layer.borderWidth = 1.0f;
cell.layer.borderColor = [[UIColor grayColor] CGColor];
cell.profilepic.layer.cornerRadius = 5;
cell.profilepic.layer.masksToBounds = YES;
cell.profilepic.layer.borderWidth = 1.0f;
cell.profilepic.layer.borderColor = [[UIColor grayColor] CGColor];
}
if ((facebook_printed == 0) && (logged_facebook == 1)) {
NSString *full_name = [NSString stringWithFormat:#"%# %#", facebook_first_name, facebook_last_name];
cell.username.text = [NSString stringWithFormat:#"%#", full_name];
cell.account_type_name.text = [NSString stringWithFormat:#"Facebook"];
NSData *facebook_imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: facebook_proffile_pic]];
UIImage *facebook_image = [[UIImage alloc] initWithData:facebook_imageData];
cell.profilepic.image = facebook_image;
facebook_printed = 1;
}
else if ((youtube_printed == 0) && (logged_youtube == 1)) {
cell.username.text = [NSString stringWithFormat:#"%#", youtube_profilename];
cell.account_type_name.text = [NSString stringWithFormat:#"YouTube"];
NSData *youtube_imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: youtube_profilepic]];
UIImage *youtube_image = [[UIImage alloc] initWithData:youtube_imageData];
cell.profilepic.image = youtube_image;
youtube_printed = 1;
}
else if ((instagram_printed == 0) && (logged_instagram == 1)) {
cell.username.text = [NSString stringWithFormat:#"%#", instagram_name_tag];
cell.account_type_name.text = [NSString stringWithFormat:#"Instagram"];
NSData *instagram_imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: instagram_profilepicture]];
UIImage *instagram_image = [[UIImage alloc] initWithData:instagram_imageData];
cell.profilepic.image = instagram_image;
instagram_printed = 1;
}
else if ((googleplus_printed == 0) && (logged_googleplus == 1)) {
cell.username.text = [NSString stringWithFormat:#"%#", googleplus_profilename];
cell.account_type_name.text = [NSString stringWithFormat:#"Google Plus"];
NSData *googleplus_imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: googleplus_profilepic]];
UIImage *googleplus_image = [[UIImage alloc] initWithData:googleplus_imageData];
cell.profilepic.image = googleplus_image;
googleplus_printed = 1;
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
return cell;
}
Maybe try reloading the table view's data once you obtain the value of the string?
[tableView reloadData];
Right after much frustration and pretty much a lot of trial and error I finally figured out that it is because of if (cell == nil) that my Custom Cell was not loading (showing in the UITableView).
I was not aware of this at all, but from what I have read online it seems that when using UiTableViews in Storyboard UI's with Custom Cells, you are NOT meant to use the control statement if (cell == nil)
Thanks to everyone who commented on this post though. I appreciate you're help.
I want to connect an my app to the database and display it in a Label.
I could connect my app to the database and display it in the UITableView.
This is what I have so far:
Viewontroller.h
#import <UIKit/UIKit.h>
#interface CartHistoryViewController : UITableViewController
{
NSMutableArray *arrayDataFromServer;
}
#end
ViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/CartGet.php? choice=history"];
NSArray *arrayImagesNames = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURL]];
strURL = #"http://localhost:8888/CartGet.php?choice=historydate";
NSArray *arrayImagesPaths = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:strURL]];
// store the result in arrayDataFromServer
arrayDataFromServer = [[NSMutableArray alloc]init];
NSEnumerator *enumForNames = [arrayImagesNames objectEnumerator];
NSEnumerator *enumForPahts = [arrayImagesPaths objectEnumerator];
id objName, objPath;
while ( objName = [enumForNames nextObject]) {
objPath = [enumForPahts nextObject];
[arrayDataFromServer addObject:[NSDictionary dictionaryWithObjectsAndKeys:objName, #"name", objPath, #"path", nil]];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [[arrayDataFromServer objectAtIndex:indexPath.row] objectForKey:#"name"];
[cell.textLabel setFont:[UIFont systemFontOfSize:20]];
cell.detailTextLabel.text = [[arrayDataFromServer objectAtIndex:indexPath.row] objectForKey:#"path"];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[[arrayDataFromServer objectAtIndex:indexPath.row] objectForKey:#"path"]]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:data];
cell.imageView.image = img;
return cell;
}
I want to be able to display it in a Label and in an ImageView instead of a cell. Please help.
Go to your Interface Builder choose your table view and make it Grouped TableView
add below code before your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [arrayDataFromServer count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 0;
}
// set header height of gropued tableview
-(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
return 120;//change this value if it is too big
}
//set header section labels
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
NSString * subject=[[arrayDataFromServer objectAtIndex:section] objectForKey:#"name"];//this line may give you error because of section easy to correct
UILabel *subjectLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 30, 100, 100)];
subjectLabel.textColor = [UIColor colorWithRed:0/256.0 green:84/256.0 blue:129/256.0 alpha:1.0];
subjectLabel.font = [UIFont fontWithName:#"Arial" size:25];
subjectLabel.text = subject;
subjectLabel.backgroundColor = [UIColor clearColor];
[subjectLabel sizeToFit];
// if you want to add image view create an imageview programatically here
// NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",[[arrayDataFromServer objectAtIndex:section] objectForKey:#"path"]]];
//NSData *data = [NSData dataWithContentsOfURL:url];
//UIImage *img = [UIImage imageWithData:data];
// UIImageView *brickAnim = [[UIImageView alloc] initWithImage:img];
// Create header view and add label as a subview choose coordinates wisely
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 120, 100, G00)];
[view addSubview:subjectLabel];
//[view addSubview:brickAnim];
return view;
}