UITableView calling the another UITableView cellForRowAtIndexPath - ios

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.

Related

Table view cells showing actual data only after scrolling once

NSArray *sectionArray;
int sectionCount=0;
NSDictionary *orderedData;
NSString *checkInStr, *checkOutStr;
NSString *govtTaxes, *enhancementTotal, *grandTotal;
- (void)viewDidLoad {
[super viewDidLoad];
[self setupTable];
[self.bookingsTableView reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)viewDidDisappear:(BOOL)animated {
if(doesSendNotification){
NSLog(#"summary view disappeared");
[[NSNotificationCenter defaultCenter] postNotificationName:#"SummaryViewDismissedNotification" object:self];
}
}
-(void)viewWillAppear:(BOOL)animated {
[self.bookingsTableView reloadData];
}
-(void)setupTable {
self.bookingsTableView.rowHeight = UITableViewAutomaticDimension;
self.bookingsTableView.estimatedRowHeight = 50.0;
sectionArray = [[SummaryModel sharedInstance] getTableSections:self.s_sendEnhancementServerDict];
orderedData = [[SummaryModel sharedInstance] getOrderedData:self.s_sendEnhancementServerDict];
[self.bookingsTableView reloadData];
}
#pragma mark- UITableview delegate and datasource methods
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if(section==0){
return 3;
} else if (section>0 && section<(sectionCount-1)){
int rows=(int)[[orderedData objectForKey:(NSString*)[sectionArray objectAtIndex:section]] count];
return rows;
} else {
return 4;
}
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return (NSString*)[sectionArray objectAtIndex:section];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier;
UITableViewCell *cell;
// UITableView *table = (UITableView*)[self.view viewWithTag:11];
if (indexPath.section==0 && indexPath.row>=0 && indexPath.row<=2) {
cellIdentifier =#"SplitCell";
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
UILabel *l1 = (UILabel*)[cell viewWithTag:1];
UILabel *l2 = (UILabel*)[cell viewWithTag:2];
if(indexPath.row==0){
l1.attributedText = [self getStyledString1:#"Hotel Name"];
l2.attributedText = [self getStyledString:self.s_propertyName];
} else if(indexPath.row==1){
l1.attributedText = [self getStyledString1:#"Arrival Date:"];
l2.attributedText = [self getStyledString:checkInStr];
} else if(indexPath.row==2){
l1.attributedText = [self getStyledString1:#"Departure Date:"];
l2.attributedText = [self getStyledString:checkOutStr];
}
} else if (indexPath.section>0 && indexPath.section<(sectionCount-1)) {
// for(int i=0;i<5;i++){
cellIdentifier=#"VerticalLabelCell";
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
UILabel *l3 = (UILabel*)[cell viewWithTag:3];
UILabel *l4 = (UILabel*)[cell viewWithTag:4];
l3.layer.backgroundColor = GOLDEN_COLOR.CGColor;
NSArray *roomTypeArray = [orderedData objectForKey:(NSString*)[sectionArray objectAtIndex:indexPath.section]];
NSDictionary *roomD = [roomTypeArray objectAtIndex:indexPath.row];
NSString *header = [roomD objectForKey:#"room_type_name"];
NSAttributedString *sH = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:#" %#",header] attributes:#{NSFontAttributeName:ARIAL_FONT_BOLD}];
l3.attributedText = sH;
int roomCount = [(NSNumber*)[roomD objectForKey:#"room_units"] intValue];
NSMutableAttributedString *labelText = [[NSMutableAttributedString alloc] init];
for(int i=0;i<roomCount;i++){
NSString *roomNo = [NSString stringWithFormat:#"\n Room # %d\n",i+1];
NSAttributedString *s = [[NSAttributedString alloc] initWithString:roomNo attributes:#{NSFontAttributeName:ARIAL_FONT_BOLD, NSUnderlineStyleAttributeName:#(NSUnderlineStyleSingle)}];
[labelText appendAttributedString:s];
NSString *adults = [NSString stringWithFormat:#" Adults: %# \t\t Max. Adults: %# \n",[roomD objectForKey:#"max_adults"],[roomD objectForKey:#"max_adults"]];
NSAttributedString *s1 = [[NSAttributedString alloc] initWithString:adults attributes:#{NSFontAttributeName:ARIAL_FONT_BOLD}];
[labelText appendAttributedString:s1];
NSArray *enhanc = [(NSArray*)[roomD objectForKey:#"room_features"] objectAtIndex:i];
for(int i=0;i<[enhanc count];i++){
[labelText appendAttributedString:[self getStyledString2:[NSString stringWithFormat:#" %#\n", [enhanc objectAtIndex:i]]]];
}
l4.attributedText = labelText;
}
} else if(indexPath.section==(sectionCount-1)){
cellIdentifier =#"SplitCell";
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
UILabel *l1 = (UILabel*)[cell viewWithTag:1];
UILabel *l2 = (UILabel*)[cell viewWithTag:2];
if(indexPath.row==0){
l1.attributedText = [self getStyledString1:#"Room Charges:"];
l2.attributedText = [self getStyledString:[NSString stringWithFormat:#"£ %#", self.s_priceOfRooms]];
}else if(indexPath.row==1){
l1.attributedText = [self getStyledString1:#"Government Taxes:"];
l2.attributedText = [self getStyledString:[NSString stringWithFormat:#"£ %#", govtTaxes]];
}else if(indexPath.row==2){
l1.attributedText = [self getStyledString1:#"Enhancement Total:"];
l2.attributedText = [self getStyledString:[NSString stringWithFormat:#"£ %#", enhancementTotal]];
}else if(indexPath.row==3){
l1.attributedText = [self getStyledString1:#"Total Charges"];
l2.attributedText = [self getStyledString:[NSString stringWithFormat:#"£ %#", grandTotal]];
}
}
return cell;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
sectionCount = (int)[sectionArray count];
return sectionCount;
}
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
view.tintColor = GOLDEN_COLOR;
}
-(NSAttributedString*)getStyledString:(NSString*)input {
NSAttributedString *str = [[NSAttributedString alloc] initWithString:input attributes:#{NSForegroundColorAttributeName:GOLDEN_COLOR, NSFontAttributeName:ARIAL_FONT}];
return str;
}
-(NSAttributedString*)getStyledString1:(NSString*)input {
NSAttributedString *str = [[NSAttributedString alloc] initWithString:input attributes:#{NSFontAttributeName:ARIAL_FONT_BOLD}];
return str;
}
-(NSAttributedString*)getStyledString2:(NSString*)input {
NSAttributedString *str = [[NSAttributedString alloc] initWithString:input attributes:#{NSFontAttributeName:ARIAL_FONT}];
return str;
}
I have made a ViewController and added a table view in it. Some data is populated in cells and then displayed.
When I run it, initially I don't see any data in my cells. But when the tableview is scrolled cells start showing the actual data. I don't understand what could be the reason. Any pointers please???
I want to dynamically resize my cells as data can be of random size. Data shows only after scrolling once.
This problem is related to using UITableViewAutomaticDimension and has been reported at other places as well. So this line of code, solved my problem:
-(void)viewDidAppear:(BOOL)animated {
[self.tableView reloadData];
}
This just reloads all the table sections and rows before displaying. So user does not experience blank rows. Refer: http://www.appcoda.com/self-sizing-cells/
You need to use reloadData in the main thread (viewDidLoad). You need to use
dispatch_async like the code below :
dispatch_async(dispatch_get_main_queue(), ^{
[self.mytable reloadData];
}
In setupTable, check sectionArray and orderedData to make sure they're not empty. Add an assertion in setupTable, e.g.,
sectionArray = [[SummaryModel sharedInstance] getTableSections:self.s_sendEnhancementServerDict];
orderedData = [[SummaryModel sharedInstance] getOrderedData:self.s_sendEnhancementServerDict];
NSAssert([sectionArray count] && [orderedData count], #"No data!"); // add this line
[self.bookingsTableView reloadData];
Swift 5+
IOS 13
Xcode 11.2.1 +
Amazing Answer
override func viewDidAppear(_ animated: Bool) {
// self.tablev.frame.origin.y = vnavigation.frame.maxY + 5
// tablevheight = self.tablev.frame.size.height
self.bgview.backgroundColor = UIColor.init(patternImage: UIImage(named: "chat_bg.png")!)
self.registerForKeyboardNotifications()
UIView.performWithoutAnimation {
tablev.beginUpdates()
tablev.endUpdates()
}
}

Adding/removing object to mutable array

I have allSpecialities array, and selectedSpecialities array. I'm downloading those arrays from the server, parse them to object and adding them to those arrays. Now, I want to check/uncheck some specialities. I've tried with containsObject, but that's not working, because those objects are not on the same memory location. This is code that I've done so far, and it's working, but I have problem how to add them to this array.
in cellForRowAtIndexPath:
for (Speciality *specTemp in self.selectedSpecialities) {
if (speciality.specialityId == specTemp.specialityId) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
break;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
in didSelect:
Speciality *speciality = [[Speciality alloc]init];
speciality = self.allSpecialities[indexPath.row];
NSMutableArray *tempSelectedSpecialities = [[NSMutableArray alloc]initWithArray:self.selectedSpecialities];
int i=0;
for (Speciality *tempSpeciality in tempSelectedSpecialities) {
if (tempSpeciality.specialityId == speciality.specialityId) {
[self.selectedSpecialities removeObjectAtIndex:i];
}
else {
}
i++;
}
[self.delegate companySpecialities:self.selectedSpecialities];
[self.specialitiesTableView reloadData];
I have declare one Mutable array in .h to store a data
NSMutableArray *selectedMarks;
assign memory in viewDidLoad
selectedMarks = [NSMutableArray new];
add and remove object in didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
TableViewCell *cell = (TableViewCell *)[self.tblview cellForRowAtIndexPath:indexPath];
NSString *strIndex=[NSString stringWithFormat:#"%ld",(long)indexPath.section];
if ([selectedMarks containsObject:strIndex])// Is selected?
{
[selectedMarks removeObject:strIndex];
}
else{
[selectedMarks addObject:strIndex];
}
}
in cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CRTableViewCellIdentifier = #"TableViewCell";
TableViewCell *cell = (TableViewCell *)[self.tblview dequeueReusableCellWithIdentifier:CRTableViewCellIdentifier];
if (cell == nil) {
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CRTableViewCellIdentifier];
}
cell.backgroundColor=[UIColor colorWithRed:122/255.0 green:196/255.0 blue:251/255.0 alpha:1];
// Check if the cell is currently selected (marked)
NSString *txtQRCodeid = [[[dictListQR objectForKey:#"boxlist"]objectAtIndex:indexPath.section]valueForKey:#"qr_code_id"];
NSString *text1 = [[[dictListQR objectForKey:#"boxlist"]objectAtIndex:indexPath.section]valueForKey:#"box_name"];
NSString *text=[NSString stringWithFormat:#"QR Code %ld with %#",indexPath.section+1,text1];
cell.isSelected = [selectedQR containsObject:txtQRCodeid] ? YES : NO;
if (cell.isSelected) {
[cell.btnSelection setImage:[UIImage imageNamed:#"check"] ];
// set image of selected
}
else{
[cell.btnSelection setImage:[UIImage imageNamed:#"uncheck"] ];
// set unselected image
}
cell.lblQRcodeText.text=text;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:15];
return cell;
}
It's Work for me

How to set a Bool value to be different for each UITableView Section

What I want to do here is set it so that if top3ArrayForSection.count-1 < 1, set the _results bool value of that respective section to NO, and so on. What's happening instead, is that _results is set to NO or YES for the entire table overall, so that I end up with a result like this:
When only the "xperia Z3 compact unlocked" section should say "no items found etc." because it has no cells, the other sections cells shouldn't.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSDictionary *currentSectionDictionary = _matchCenterArray[section];
NSArray *top3ArrayForSection = currentSectionDictionary[#"Top 3"];
if (top3ArrayForSection.count-1 < 1){
_results = NO;
_rowCount = 1;
}
else if(top3ArrayForSection.count-1 >= 1){
_results = YES;
_rowCount = top3ArrayForSection.count-1;
}
return _rowCount;
}
// Cell layout
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Initialize cell
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
// if no cell could be dequeued create a new one
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// No cell seperators = clean design
tableView.separatorColor = [UIColor clearColor];
if (_results == NO) {
// title of the item
cell.textLabel.text = #"No items found, but we'll keep a lookout for you!";
cell.textLabel.font = [UIFont boldSystemFontOfSize:12];
}
else if (_results == YES) {
// title of the item
cell.textLabel.text = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Title"];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
// price of the item
cell.detailTextLabel.text = [NSString stringWithFormat:#"$%#", _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Price"]];
cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f];
// image of the item
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Image URL"]]];
[[cell imageView] setImage:[UIImage imageWithData:imageData]];
}
return cell;
}
Your instance variable _results is one-dimensional. You could replace it with an NSArray and store the values individually, or you could change the logic in your code as such:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSDictionary *currentSectionDictionary = _matchCenterArray[section];
NSArray *top3ArrayForSection = currentSectionDictionary[#"Top 3"];
return (top3ArrayForSection.count-1 < 1) ? 1 : top3ArrayForSection.count-1;
}
// Cell layout
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Initialize cell
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
// if no cell could be dequeued create a new one
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// No cell seperators = clean design
tableView.separatorColor = [UIColor clearColor];
NSDictionary *currentSectionDictionary = _matchCenterArray[indexPath.section];
NSArray *top3ArrayForSection = currentSectionDictionary[#"Top 3"];
if (top3ArrayForSection.count-1 < 1) {
// title of the item
cell.textLabel.text = #"No items found, but we'll keep a lookout for you!";
cell.textLabel.font = [UIFont boldSystemFontOfSize:12];
}
else {
// title of the item
cell.textLabel.text = _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Title"];
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
// price of the item
cell.detailTextLabel.text = [NSString stringWithFormat:#"$%#", _matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Price"]];
cell.detailTextLabel.textColor = [UIColor colorWithRed:0/255.0f green:127/255.0f blue:31/255.0f alpha:1.0f];
// image of the item
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_matchCenterArray[indexPath.section][#"Top 3"][indexPath.row+1][#"Image URL"]]];
[[cell imageView] setImage:[UIImage imageWithData:imageData]];
}
return cell;
}

UITableView set checkbox state from database values

I am storing checkbox values (true/false) in database. I want to set checkbox checked/unchecked depending on the values stored in database. how to do that ? my code is,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%i",indexPath.row];
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:18.0];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.frame=CGRectMake(75.0, 50.0, 150.0, 20.0);
cell.textLabel.text=[listArray objectAtIndex:indexPath.row];
NSLog(#"Checked arr size %i",[checkedArr count]);
BOOL checked = [[checkedArr objectAtIndex:indexPath.row] boolValue];
UIImage *image = (checked) ? [UIImage imageNamed:#"white_bg.png"] : [UIImage imageNamed:#"tick.png"];
cell.accessoryView = [[UIImageView alloc] initWithImage:image];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
BOOL checked = [[checkedArr objectAtIndex:indexPath.row] boolValue];
[checkedArr removeObjectAtIndex:indexPath.row];
[checkedArr insertObject:(checked) ? #"FALSE":#"TRUE" atIndex:indexPath.row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIImage *newImage = (checked) ? [UIImage imageNamed:#"tick.png"] : [UIImage imageNamed:#"white_bg.png"];
cell.accessoryView=[[UIImageView alloc] initWithImage:newImage];
NSLog(#"Val is %i",val);
NSLog(#"selected is %#",[listArray objectAtIndex:indexPath.row]);
}
I am storing those values in database using an array checkedArr.
[dbObj insertQuestData:Question answers:listArray checkVal:checkedArr];
here dbObj is database object, others are values that i am storing to database.
Please let me know how to achieve the same.
The list array and checked array should be mutable array sent to database function which fills up the data.
self.listArray = [NSMutableArray array];
self.checkedArray = [NSMutableArray array];
[dbObj insertQuestData:Question answers:self.listArray checkVal:self.checkedArray];
// [self insertList:self.listArray andChecks:self.checkedArray];
The insertQuestData methods should fill up data like this -
- (void) insertList:(NSMutableArray *)list andChecks:(NSMutableArray *)checks
{
for (int i = 0; i < 100; i++) {
[list addObject:[NSString stringWithFormat:#"item %d", i]];
BOOL checkValue = (i % 4) == 0 ? YES : NO;
[checks addObject:[NSNumber numberWithBool:checkValue]];
}
}
The table datasource methods should be like this - (notice the commented line as correction to your code)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.listArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = #"CellIdentifier";//[NSString stringWithFormat:#"Cell%i",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
// cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:18.0];
// cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// cell.textLabel.frame=CGRectMake(75.0, 50.0, 150.0, 20.0);
cell.textLabel.text=[self.listArray objectAtIndex:indexPath.row];
NSLog(#"Checked arr size %i",[self.checkedArray count]);
BOOL checked = [[self.checkedArray objectAtIndex:indexPath.row] boolValue];
UIImage *image = (!checked) ? [UIImage imageNamed:#"white_bg.png"] : [UIImage imageNamed:#"tick.png"];
cell.accessoryView = [[UIImageView alloc] initWithImage:image];
return cell;
}
This is what my sample code show on iPhone - [every 4th row is (green)ticked/selected and others are grey/unselected]
Feel free to ask if you have any specific questions / issues you face.

UIImageView in UITableViewCell repeat

I have a bug.
I want to display a UIImageView on cells at special indexPath.row, but these UIImageView repeat while I scroll.
Exemple: I display my UIImageView on a cell indexPath.row == 0, if I scroll down, I see my UIImageView on the cell at indexPath.row == 8.
Here is my code:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell = [self getCellContentView:CellIdentifier];
}
UILabel *lblTemp1 = (UILabel *)[cell viewWithTag:1];
UIImageView *imgRead = (UIImageView *)[cell viewWithTag:6];
[cell.contentView insertSubview:imgRead aboveSubview:lblTemp1];
contentDictio = [dict objectAtIndex:indexPath.row];
lblTemp1.text = [contentDictio objectForKey:#"title"];
NSArray *paths_id = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath_id = ([paths_id count] > 0) ? [paths_id objectAtIndex:0] : nil;
NSString *path_id = [basePath_id stringByAppendingPathComponent:#"id.plist"];
NSMutableArray *mut_array_id = [[NSArray arrayWithContentsOfFile:path_id] mutableCopy];
NSMutableDictionary *c0 = [[NSMutableDictionary alloc] init];
NSString *idPlistData = [contentDictio objectForKey:#"id"];
for(c0 in mut_array_id) {
if([[c0 objectForKey:#"id"] isEqualToString:idPlistData]) {
[imgRead setImage:[UIImage imageNamed:#"read"]];
}
else {
}
}
}
return cell;
}
- (UITableViewCell *) getCellContentView:(NSString *)cellIdentifier {
CGRect Label1Frame = CGRectMake(kTableCellSmallMargin*2 + 60, kTableCellSmallMargin, 240, 25);
UILabel *lblTemp;
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier] autorelease];
//Initialize Label with tag 1.
lblTemp = [[UILabel alloc] initWithFrame:Label1Frame];
lblTemp.tag = 1;
lblTemp.backgroundColor = [UIColor clearColor];
[lblTemp setFont: [UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:15.0]];
[cell.contentView addSubview:lblTemp];
[lblTemp release];
UIImageView *read=[[UIImageView alloc] initWithFrame:CGRectMake(kTableCellSmallMargin, kTableCellSmallMargin, 60, 60)];
read.backgroundColor=[UIColor clearColor];
read.tag = 6;
[cell.contentView addSubview:read];
[read release];
return cell;
}
Thanks...
The cell is cached, so you have to clear it when you want no image, like this:
BOOL found = NO;
for(c0 in mut_array_id) {
if([[c0 objectForKey:#"id"] isEqualToString:idPlistData]) {
[imgRead setImage:[UIImage imageNamed:#"read"]];
found = YES;
}
else {
}
}
if (!found)
{
[imgRead setImage:nil];
}

Resources