UITableView select a row per section - ios

I would like to make a selection like this
How can I change my
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
delegate method to work in accordance with my requirement.

Why so complicated? Just deselect all cells of the same section before the user selects a new one.
First allow multiple selection for your UITableView. Then implement this delegate method:
Swift 3 version:
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath?
{
for vcip in tableView.indexPathsForSelectedRows ?? [] {
if vcip.section == indexPath.section && vcip.item != indexPath.item {
tableView.deselectRow(at: vcip, animated: false)
}
}
return indexPath
}

Keep a property in your view controller called selectedRow, which represents the indexPath of tableview that represents the checked item in a table section.
In your view controller's -tableView:cellForRowAtIndexPath: delegate method, set the accessoryType of the cell to UITableViewCellAccessoryCheckmark if the cell's indexPath equals the selectedRow indexpath value. Otherwise, set it to UITableViewCellAccessoryNone.
In your view controller's -tableView:didSelectRowAtIndexPath: delegate method, set the selectedRow value to the indexPath.row that is selected, e.g.: self.selectedRow = indexPath.row

This won't be a good solution.
Use a NSMutableArray for storing the selected sections.
NSMutableArray *selectedSections; //instance variable
selectedSections= [[NSMutableArray alloc] init]; //in viewDidLoad
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSNumber *section = [NSNumber numberWithInt:indexPath.section];
if([selectedSections containsObject:section]
return nil;
else
{
[selectedSections addObject:section];
return indexPath;
}
}
When you deselect a row write the below code there:
[selectedSections removeObject:[NSNumber numberWithInt:indexPath.section]];

LimeRed has a great answer elsewhere in this thread, but it is not complete. The key issue is that the OP needs to have the accessory checkmark removed. Simply calling deselectRow will not remove the checkmark. Per the documentation, deselectRow does not call the delegate method tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) where the removal of the checkmark code might be located. Therefore you need handle this removal as part of the code that LimeRed wrote.
Here is a more complete implementation that removes the accessory checkmark again based on LimeRed's solution:
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath?
{
for path in tableView.indexPathsForSelectedRows ?? []
{
if path.section == indexPath.section && path.item != indexPath.item
{
let cell = tableView.cellForRow(at: path)
cell?.accessoryType = UITableViewCellAccessoryType.none
tableView.deselectRow(at: path, animated: false)
}
}
return indexPath
}

try like this,
In .h
#property (nonatomic, retain) NSIndexPath *checkedIndexPath;
In .m
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section==0)
{
// to check and Uncheck the row
if(self.checkedIndexPath)
{
UITableViewCell* uncheckCell = [tableView1
cellForRowAtIndexPath:self.checkedIndexPath];
uncheckCell.accessoryType = UITableViewCellAccessoryNone;
}
if([self.checkedIndexPath isEqual:indexPath])
{
self.checkedIndexPath = nil;
}
else
{
UITableViewCell* cell = [tableView1 cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
self.checkedIndexPath = indexPath;
}
}
}

This one's gonna be ViewController.h
#interface ViewController : UITableViewController
{
NSMutableArray *list;
NSMutableArray *sectionList;
NSIndexPath *oldIndexPath0;
int row0;
NSIndexPath *oldIndexPath1;
int row1;
NSIndexPath *oldIndexPath2;
int row2;
NSIndexPath *oldIndexPath3;
int row3;
NSString *othersString;
NSString *timeString;
NSString *pRoomString;
NSString *parkingString;
NSString *smokingString;
NSString *select0;
NSString *select1;
NSString *select2;
NSString *select3;
}
#end
This one's ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewWillAppear:(BOOL)animated
{
// initial row by 100;
row0 = 100;
row1 = 100;
row2 = 100;
row3 = 100;
// initial strings by #”"
othersString = [NSString stringWithFormat:#""];
timeString = [NSString stringWithFormat:#""];
pRoomString = [NSString stringWithFormat:#""];
parkingString = [NSString stringWithFormat:#""];
smokingString = [NSString stringWithFormat:#""];
select0 = #"";
select1 = #"";
select2 = #"";
select3 = #"";
// Get row index
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:#"tmp/rowString.txt"];
NSData *rowData = [fileManager contentsAtPath:fileName];
// From NSData to NSString
NSString *rowString = [[NSString alloc] initWithData:rowData encoding:NSUTF8StringEncoding];
if (rowString) {
// spit row string
NSArray *rowArray = [rowString componentsSeparatedByString:#":"];
for (int i=0; i<[rowArray count]; i++) {
NSString *indexVal = [rowArray objectAtIndex:i];
if ([indexVal length] != 0) {
// set row value
if (i == 0) {
NSString *row0Str = [rowArray objectAtIndex:0];
row0 = [row0Str intValue];
}
if (i == 1) {
NSString *row1Str = [rowArray objectAtIndex:1];
row1 = [row1Str intValue];
}
if (i == 2) {
NSString *row2Str = [rowArray objectAtIndex:2];
row2 = [row2Str intValue];
}
if (i == 3) {
NSString *row3Str = [rowArray objectAtIndex:3];
row3 = [row3Str intValue];
}
}
}
}
// Update the view with current data before it is displayed.
[super viewWillAppear:animated];
//Initialize the array.
list = [[NSMutableArray alloc] initWithCapacity:0];
sectionList = [[NSMutableArray alloc] initWithCapacity:0];
// section header
NSArray *sectionHeaderArray = [NSArray arrayWithObjects:#"01",#"02",#"03",#"04", nil];
NSDictionary *sectionHeaderDic = [NSDictionary dictionaryWithObject:sectionHeaderArray forKey:#"section"];
[sectionList addObject:sectionHeaderDic];
// time list
NSArray *timeArray = [NSArray arrayWithObjects:#"time 01",#"time 01",#"time 01", nil];
NSDictionary *timeDic = [NSDictionary dictionaryWithObject:timeArray forKey:#"time"];
// private room
NSArray *pRoomArray = [NSArray arrayWithObjects:#"room 01",#"room 02", nil];
NSDictionary *pRoomDic = [NSDictionary dictionaryWithObject:pRoomArray forKey:#"pRoom"];
// parking
NSArray *parkingArray = [NSArray arrayWithObjects:#"park 01",#"park 02",#"park 03", nil];
NSDictionary *parkingDic = [NSDictionary dictionaryWithObject:parkingArray forKey:#"parking"];
// smoking
NSArray *smokingArray = [NSArray arrayWithObjects:#"smoke 01",#"smoke 02",#"smoke 03", nil];
NSDictionary *smokingDic = [NSDictionary dictionaryWithObject:smokingArray forKey:#"smoking"];
// add all dictionary to list
[list addObject:timeDic];
[list addObject:pRoomDic];
[list addObject:parkingDic];
[list addObject:smokingDic];
// Scroll the table view to the top before it appears
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//Number of section
return [list count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//Get the dictionary object
NSDictionary *dictionary = [list objectAtIndex:section];
NSArray *array;
switch (section) {
case 0:
// time array
array = [dictionary objectForKey:#"time"];
break;
case 1:
// pRoom array
array = [dictionary objectForKey:#"pRoom"];
break;
case 2:
// parking array
array = [dictionary objectForKey:#"parking"];
break;
case 3:
// smoking array
array = [dictionary objectForKey:#"smoking"];
break;
default:
break;
}
//Number of rows
return [array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Budget";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
UITableViewCellStyleSubtitle;
}
//Get the dictionary object
NSDictionary *dictionary = [list objectAtIndex:indexPath.section];
NSArray *array;
switch (indexPath.section) {
case 0:
// time array
array = [dictionary objectForKey:#"time"];
if (indexPath.row == row0 ) {
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
break;
case 1:
// pRoom array
array = [dictionary objectForKey:#"pRoom"];
if (indexPath.row == row1) {
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
break;
case 2:
// parking array
array = [dictionary objectForKey:#"parking"];
if (indexPath.row == row2) {
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
break;
case 3:
// smoking array
array = [dictionary objectForKey:#"smoking"];
if (indexPath.row == row3) {
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
break;
default:
break;
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
NSLog(#"index cell");
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *title = nil;
//Get the dictionary object
NSDictionary *dictionary = [sectionList objectAtIndex:0];
NSArray *array = [dictionary objectForKey:#"section"];
title = [array objectAtIndex:section];
return title;
}
#pragma mark -
#pragma mark Table view selection
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
switch(indexPath.section)
{
case 0:
{
UITableViewCell *cell1 = [tableView cellForRowAtIndexPath:indexPath];
if ([[tableView cellForRowAtIndexPath:indexPath ] accessoryType] == UITableViewCellAccessoryCheckmark) {
cell1.accessoryType = UITableViewCellAccessoryNone;
row0 = 100;
timeString = #"";
}else {
NSIndexPath *SIndexPath0 = [NSIndexPath indexPathForRow:row0 inSection:0];
if ([[tableView cellForRowAtIndexPath:SIndexPath0 ] accessoryType] == UITableViewCellAccessoryCheckmark) {
[[tableView cellForRowAtIndexPath:SIndexPath0] setAccessoryType:UITableViewCellAccessoryNone];
}
if (oldIndexPath0 == nil) {
oldIndexPath0 = indexPath;
}
UITableViewCell *cell2 = nil;
if (oldIndexPath0 != indexPath) {
cell2 = [tableView cellForRowAtIndexPath:oldIndexPath0];
}
cell1.accessoryType = UITableViewCellAccessoryCheckmark;
if (cell2) {
cell2.accessoryType = UITableViewCellAccessoryNone;
}
//Get the dictionary object
NSDictionary *dictionary = [list objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"time"];
timeString = [array objectAtIndex:indexPath.row];
row0 = indexPath.row;
oldIndexPath0 = nil;
}
select0 = #"marked";
break;
}
case 1:
{
UITableViewCell *cell1 = [tableView cellForRowAtIndexPath:indexPath];
if ([[tableView cellForRowAtIndexPath:indexPath ] accessoryType] == UITableViewCellAccessoryCheckmark) {
cell1.accessoryType = UITableViewCellAccessoryNone;
row1 = 100;
pRoomString = #"";
}else {
NSIndexPath *SIndexPath1 = [NSIndexPath indexPathForRow:row1 inSection:1];
if ([[tableView cellForRowAtIndexPath:SIndexPath1 ] accessoryType] == UITableViewCellAccessoryCheckmark) {
[[tableView cellForRowAtIndexPath:SIndexPath1] setAccessoryType:UITableViewCellAccessoryNone];
}
if (oldIndexPath1 == nil) {
oldIndexPath1 = indexPath;
}
UITableViewCell *cell2 = nil;
if (oldIndexPath1 != indexPath) {
cell2 = [tableView cellForRowAtIndexPath:oldIndexPath1];
}
cell1.accessoryType = UITableViewCellAccessoryCheckmark;
if (cell2) {
cell2.accessoryType = UITableViewCellAccessoryNone;
}
//Get the dictionary object
NSDictionary *dictionary = [list objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"pRoom"];
pRoomString = [array objectAtIndex:indexPath.row];
row1 = indexPath.row;
oldIndexPath1 = nil;
}
select1 = #"marked";
break;
}
case 2:
{
UITableViewCell *cell1 = [tableView cellForRowAtIndexPath:indexPath];
if ([[tableView cellForRowAtIndexPath:indexPath ] accessoryType] == UITableViewCellAccessoryCheckmark) {
cell1.accessoryType = UITableViewCellAccessoryNone;
row2 = 100;
parkingString = #"";
}else {
NSIndexPath *SIndexPath2 = [NSIndexPath indexPathForRow:row2 inSection:2];
if ([[tableView cellForRowAtIndexPath:SIndexPath2 ] accessoryType] == UITableViewCellAccessoryCheckmark) {
[[tableView cellForRowAtIndexPath:SIndexPath2] setAccessoryType:UITableViewCellAccessoryNone];
}
if (oldIndexPath2 == nil) {
oldIndexPath2 = indexPath;
}
UITableViewCell *cell2 = nil;
if (oldIndexPath2 != indexPath) {
cell2 = [tableView cellForRowAtIndexPath:oldIndexPath2];
}
cell1.accessoryType = UITableViewCellAccessoryCheckmark;
if (cell2) {
cell2.accessoryType = UITableViewCellAccessoryNone;
}
//Get the dictionary object
NSDictionary *dictionary = [list objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"parking"];
parkingString = [array objectAtIndex:indexPath.row];
row2 = indexPath.row;
oldIndexPath2 = nil;
}
select2 = #"marked";
break;
}
case 3:
{
UITableViewCell *cell1 = [tableView cellForRowAtIndexPath:indexPath];
if ([[tableView cellForRowAtIndexPath:indexPath ] accessoryType] == UITableViewCellAccessoryCheckmark) {
cell1.accessoryType = UITableViewCellAccessoryNone;
row3 = 100;
smokingString = #"";
}else {
NSIndexPath *SIndexPath3 = [NSIndexPath indexPathForRow:row3 inSection:3];
if ([[tableView cellForRowAtIndexPath:SIndexPath3 ] accessoryType] == UITableViewCellAccessoryCheckmark) {
[[tableView cellForRowAtIndexPath:SIndexPath3] setAccessoryType:UITableViewCellAccessoryNone];
}
if (oldIndexPath3 == nil) {
oldIndexPath3 = indexPath;
}
UITableViewCell *cell2 = nil;
if (oldIndexPath3 != indexPath) {
cell2 = [tableView cellForRowAtIndexPath:oldIndexPath3];
}
cell1.accessoryType = UITableViewCellAccessoryCheckmark;
if (cell2) {
cell2.accessoryType = UITableViewCellAccessoryNone;
}
//Get the dictionary object
NSDictionary *dictionary = [list objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"smoking"];
smokingString = [array objectAtIndex:indexPath.row];
row3 = indexPath.row;
oldIndexPath3 = nil;
}
select3 = #"marked";
break;
}
default:
break;
}
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
// Cancle button and add an event handler
self.navigationItem.leftBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:#"Cancle"
style:UIBarButtonSystemItemCancel
target:self
action:#selector(handleCancle:)];
// Cancle button and add an event handler
self.navigationItem.rightBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:#"Use"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(handleUse:)];
}
- (void) handleCancle:(id)sender
{
// pop the controller
[self.navigationController popViewControllerAnimated:YES];
}
- (void) handleUse:(id)sender{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *fileName;
// Get row index value
fileName = [NSHomeDirectory() stringByAppendingPathComponent:#"tmp/othersString.txt"];
NSData *rowValData = [fileManager contentsAtPath:fileName];
// From NSData to NSString
NSString *rowValString = [[NSString alloc] initWithData:rowValData encoding:NSUTF8StringEncoding];
NSString *oldTimeString = #"";
NSString *oldpRoomString = #"";
NSString *oldParkingString = #"";
NSString *oldSmokingString = #"";
if (rowValString) {
// spit row string
NSArray *rowValArray = [rowValString componentsSeparatedByString:#":"];
for (int i=0; i<[rowValArray count]; i++) {
if ([rowValArray objectAtIndex:i] != #"") {
// set row value
if (i == 0 ) {
oldTimeString = [rowValArray objectAtIndex:0];
}
if (i == 1 ) {
oldpRoomString = [rowValArray objectAtIndex:1];
}
if (i == 2 ) {
oldParkingString = [rowValArray objectAtIndex:2];
}
if (i == 3) {
oldSmokingString = [rowValArray objectAtIndex:3];
}
}
}
}
if (select0 == #"") {
timeString = oldTimeString;
}
if (select1 == #"") {
pRoomString = oldpRoomString;
}
if (select2 == #"") {
parkingString = oldParkingString;
}
if (select3 == #"") {
smokingString = oldSmokingString;
}
// make othersString string
othersString = [NSString stringWithFormat:#"%#:%#:%#:%#", timeString, pRoomString, parkingString, smokingString];
// write othersString to othersString.txt file
fileName= [NSHomeDirectory() stringByAppendingPathComponent:#"tmp/othersString.txt"];
NSData *othersData = [othersString dataUsingEncoding:NSUTF8StringEncoding];
[fileManager createFileAtPath:fileName contents:othersData attributes:nil];
// make row data in string
NSString *rowString = [NSString stringWithFormat:#"%i:%i:%i:%i", row0,row1,row2,row3];
// write othersString to othersString.txt file
fileName = [NSHomeDirectory() stringByAppendingPathComponent:#"tmp/rowString.txt"];
NSData *rowData = [rowString dataUsingEncoding:NSUTF8StringEncoding];
[fileManager createFileAtPath:fileName contents:rowData attributes:nil];
// pop the controller
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
[list release];
}
#end
Got this stuff from this post, as this was in Japanese I changed it. Thanks to the author.

After a lot of modifications I have arrived with this
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [aTableView cellForRowAtIndexPath:indexPath];
if(indexPath.section == 0)
{
if([section1Rows count] == 0)
{
[section1Rows addObject:[NSNumber numberWithInt:indexPath.row]];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
[section1Rows removeObjectAtIndex:0];
for (UITableViewCell *cell in [tabview visibleCells]) {
cell.accessoryType = UITableViewCellAccessoryNone;
}
[section1Rows addObject:[NSNumber numberWithInt:indexPath.row]];
NSLog(#"%#",section1Rows);
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
if(indexPath.section == 1)
{
if([section2Rows count] == 0)
{
[section2Rows addObject:[NSNumber numberWithInt:indexPath.row]];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
[section2Rows removeObjectAtIndex:0];
for (UITableViewCell *cell in [tabview visibleCells]) {
cell.accessoryType = UITableViewCellAccessoryNone;
}
[section2Rows addObject:[NSNumber numberWithInt:indexPath.row]];
NSLog(#"%#",section2Rows);
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
if(indexPath.section == 2)
{
if([section3Rows count] == 0)
{
[section3Rows addObject:[NSNumber numberWithInt:indexPath.row]];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
[section3Rows removeObjectAtIndex:0];
for (UITableViewCell *cell in [tabview visibleCells]) {
cell.accessoryType = UITableViewCellAccessoryNone;
}
[section3Rows addObject:[NSNumber numberWithInt:indexPath.row]];
NSLog(#"%#",section3Rows);
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
}
I'll explain the problem in steps,
I have selected a row in 3 sections, If I select a row again in any of the sections... then everything goes haywire. How can I deselect the previously selected row and highlight the then selected row?
Thanks.

Related

UItableview scrollsToTop is not working when click on button ios

I am having uicollection scrolling in horizontal direction , inside the collection view cell i have two table view - one _tablewView
-another _tblnoti , i have added a button for collapsing the order card , on click of that i want to scroll _tableView to the top , but its not working
on click of drop downbutton i m reloading the table view inside that
- (IBAction)btnDropdownclick:(UIButton*)sender
{
NSIndexPath *indesss = [NSIndexPath indexPathForItem:sender.tag-300 inSection:0];
CollectionViewCell *cell = (CollectionViewCell*) [_InnercollectionView cellForItemAtIndexPath:indesss];
_flag =indesss.item;
shouldCellBeExpanded = !shouldCellBeExpanded;
if(shouldCellBeExpanded)
{
[sender setImage:[UIImage imageNamed:#"uparrow.png"] forState:UIControlStateNormal];
}
else
{
[sender setImage:[UIImage imageNamed:#"downarrow.png"] forState:UIControlStateNormal];
}
cell.shouldCellBeExpanded = !cell.shouldCellBeExpanded ;
[_InnercollectionView performBatchUpdates:^{
[cell.tabelView reloadData];
} completion:^(BOOL finished) {
}];
}
below is code in cell class
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(_shouldCellBeExpanded){
_heightcheckview.constant = _tabelView.contentSize.height+120;
_tblheight.constant = _tabelView.contentSize.height+20;
}
else
{
_tabelView.scrollsToTop = YES;
_heightcheckview.constant = 195;
_tblheight.constant = 105;
}
if (tableView == _tblNoti) {
static NSString *MyIdentifier = #"noticell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
// self.tblheight .constant = tableView.contentSize.height;
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier] ;
}
// FoodDescModalClass *orderDataTypess;
if(!(self.arrayforNoti.count == 0))
{
NSDictionary *diction = [self.arrayforNoti objectAtIndex:indexPath.row];
UILabel *lbl = (UILabel*)[cell.contentView viewWithTag:2345];
lbl.text = [diction valueForKey:#"data"];
}
return cell;
}
else if (tableView == _tabelView){
static NSString *MyIdentifier = #"maineecell";
CollTableViewCell *cells = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
// self.tblheight .constant = tableView.contentSize.height;
if (cells == nil)
{
cells = [[CollTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier] ;
}
if(_havecomment)
{
if(indexPath.row == self.arrayforitems.count)
{
UITableViewCell* celld = [tableView dequeueReusableCellWithIdentifier:#"commentcell"];
UILabel *lblcomment = [celld.contentView viewWithTag:4545];
lblcomment.text = _finalcomment;
lblcomment.layer.borderWidth = 1.0f ;
lblcomment.layer.cornerRadius = 4.0f ;
lblcomment.layer.masksToBounds = YES;
return celld;
}else{
NSDictionary*dict = [self.arrayforitems objectAtIndex:indexPath.row];
cells.lblName.text= [dict valueForKey:#"item"];
cells.lblPrice.text = [dict valueForKey:#"price"];
cells.lblquantity.text = [dict valueForKey:#"qty"];
NSString*type = [dict valueForKey:#"type"];
if([type isEqualToString:#"1"])
{
cells.imgveg.image=[UIImage imageNamed:#"veg"];
}
else if([type isEqualToString:#"2"])
{
cells.imgveg.image=[UIImage imageNamed:#"nonveg"];
}
else
{
cells.imgveg.image=[UIImage imageNamed:#"drink.png"];
}
cells.lblquantity.layer.borderWidth = 1.0f ;
cells.lblquantity.layer.cornerRadius = 4.0f ;
cells.lblquantity.layer.masksToBounds = YES;
}
}
else{
NSDictionary*dict = [self.arrayforitems objectAtIndex:indexPath.row];
cells.lblName.text= [dict valueForKey:#"item"];
cells.lblPrice.text = [dict valueForKey:#"price"];
cells.lblquantity.text = [dict valueForKey:#"qty"];
NSString*type = [dict valueForKey:#"type"];
if([type isEqualToString:#"1"])
{
cells.imgveg.image=[UIImage imageNamed:#"veg"];
}
else if([type isEqualToString:#"2"])
{
cells.imgveg.image=[UIImage imageNamed:#"nonveg"];
}
else
{
cells.imgveg.image=[UIImage imageNamed:#"drink.png"];
}
cells.lblquantity.layer.borderWidth = 1.0f ;
cells.lblquantity.layer.cornerRadius = 4.0f ;
cells.lblquantity.layer.masksToBounds = YES;
}
return cells;
}
else
{
return nil;
}}
screen shots are below
follow in sequence
http://prntscr.com/du4p2f
http://prntscr.com/du4p00
http://prntscr.com/du4q1t

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

Using BOOL objects in NSMutableArray to determine cell statuses

I'm using an NSMutableArray referenced as 'stateArray'. stateArray needs to simply hold the BOOL value for my cells to determine whether or not they are selected. here's my code..
stateArray in my .h:
#property (nonatomic, strong) NSMutableArray *stateArray;
Then stateArray is not synthesized. It needs to be filled with NO throughout the array, so that when the cell becomes selected, NO can be replaced by YES. Currently this code is printing 0's for stateArray for every cell(the NSLog is in the if (showCheckmark == YES) from my cellForRowAtIndexPath:).
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[[UITableViewCell appearance] setTintColor:[UIColor colorWithHexString:#"#669900"]];
#define CHECK_NULL_STRING(str) ([str isKindOfClass:[NSNull class]] || !str)?#"":str
static NSString *CellIdentifier = #"inviteCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//Customization
cell.textLabel.highlightedTextColor = [UIColor colorWithHexString:#"#669900"];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.backgroundColor = [UIColor blackColor];
cell.textLabel.textColor = [UIColor whiteColor];
//Ignore this, it's for UISearchBar
BOOL isSearching = tableView != self.tableView;
NSArray *arrayToUse = (isSearching ? searchResults : contactsObjects);
id p = arrayToUse[indexPath.row];
NSString *fName = (__bridge_transfer NSString *)(ABRecordCopyValue((__bridge ABRecordRef)(p), kABPersonSortByFirstName));
NSString *lName = (__bridge_transfer NSString *)(ABRecordCopyValue((__bridge ABRecordRef)(p), kABPersonSortByLastName));
cell.textLabel.text = [NSString stringWithFormat:#"%# %#", CHECK_NULL_STRING(fName), CHECK_NULL_STRING(lName)];
_stateArray = [NSMutableArray array];
for (int i = 0 ; i != contactsObjects.count ; i++) [_stateArray addObject:#(NO)];
BOOL showCheckmark = [[_stateArray objectAtIndex:indexPath.row] boolValue];
if (showCheckmark == YES)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
NSLog(#"It hit showCheckmark = YES, and stateArray is %#",_stateArray[indexPath.row]);
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
NSLog(#"It hit showCheckmark = NO, and stateArray is %#",_stateArray[indexPath.row]);
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
id object = contactsObjects[indexPath.row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[_stateArray replaceObjectAtIndex:indexPath.row withObject:#(YES)];
[selectedObjects addObject:object];
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
[_stateArray replaceObjectAtIndex:indexPath.row withObject:#(NO)];
[selectedObjects removeObject:object];
}
//slow-motion selection animation.
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
To keep track on selected items, use a Dictionary instead of NSMutableArray and keep the indexPath.row as Key and selection as curresponding Value.
Also instead of doing these operations with array of BOOL's , you can update the code as below.
#property (nonatomic, strong) NSMutableDictionary * selectedRowCollection;
- (void)viewDidLoad{
self.selectedRowCollection = [[NSMutableDictionary alloc] init];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
id object = contactsObjects[indexPath.row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[self.selectedRowCollection setObject:#"1" forKey:[NSString stringWithFormat:#"%d",indexPath.row]];
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
[self.selectedRowCollection removeObjectForKey:[NSString stringWithFormat:#"%d",indexPath.row]];
}
//slow-motion selection animation.
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
BOOL showCheckmark = [[self.selectedRowCollection valueForKey:[NSString stringWithFormat:#"%d",indexPath.row]] boolValue];
if (showCheckmark == YES)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
Note: Don't forget remove the dictionary items from dictionary while reloading a new tableview dataset.
BOOL values are wrapped with NSNumber, that's why you get 0's:
_stateArray = [NSMutableArray array];
for (int i = 0 ; i != contactsObjects.count ; i++) [_stateArray addObject:#(NO)];
BOOL showCheckmark = [[_stateArray objectAtIndex:indexPath.row] boolValue];
if (showCheckmark == YES)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
NSLog(#"It hit showCheckmark = YES, and stateArray is %#",[[_stateArray objectAtIndex:indexPath.row] boolValue] ? #"YES" : #"NO");
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
NSLog(#"It hit showCheckmark = NO, and stateArray is %#",[[_stateArray objectAtIndex:indexPath.row] boolValue] ? #"YES" : #"NO");
}
BOOL is not object, so you cannot use the %# format specifier. You need to handle this manually
Try this,
Update your loop to populate _stateArray by
for (int i = 0 ; i != contactsObjects.count ; i++) {
[_stateArray addObject:[NSNumber numberWithBool:NO]];
}

iOS: How to save only one checkmark (for UITableView) in NSUserDefaults?

i have a question regarding NSUserDefaults. I am trying to save the checkmark that i place on a cell and then retrieve it when the app crashes or when user closes app and so on. I tried to use this post post as a guide, but no luck, but here's what i have so far. The code from the post works, however, i only need one checkmark to be saved rather than many. How would i achieve this?
#implementation ClientsViewController
#synthesize clientsInt; // This is just a variable that helps me do the drill down part of the rootviewcontroller
#synthesize checkedIndexPath;
- (NSString *)getKeyForIndex:(int)index
{
return [NSString stringWithFormat:#"KEY%d",index];
}
- (BOOL) getCheckedForIndex:(int)index
{
if([[[NSUserDefaults standardUserDefaults] valueForKey:[self getKeyForIndex:index]] boolValue]==YES)
{
return YES;
}
else
{
return NO;
}
}
- (void) checkedCellAtIndex:(int)index
{
BOOL boolChecked = [self getCheckedForIndex:index];
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:!boolChecked] forKey:[self getKeyForIndex:index]];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
if([self getCheckedForIndex:indexPath.row]==YES)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
// Configure the cell...
if (clientsInt == 0) {
cell.textLabel.text = [array1 objectAtIndex:indexPath.row];
}
else if (clientsInt == 1) {
cell.textLabel.text = [array2 objectAtIndex:indexPath.row];
}
else if (clientsInt == 2) {
cell.textLabel.text = [array3 objectAtIndex:indexPath.row];
}
else if (clientsInt == 3) {
cell.textLabel.text = [array4 objectAtIndex:indexPath.row];
}
if([self.checkedIndexPath isEqual:indexPath])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Uncheck the previous checked row
if(self.checkedIndexPath)
{
UITableViewCell* uncheckCell = [tableView cellForRowAtIndexPath:self.checkedIndexPath];
uncheckCell.accessoryType = UITableViewCellAccessoryNone;
}
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
self.checkedIndexPath = indexPath;
[self checkedCellAtIndex:indexPath.row];
if([self getCheckedForIndex:indexPath.row]==YES)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
Maybe try something like this every time the user checks a row:
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:index] forKey:#"kCheckedBoxKey"];
Since each time, you would save the index under the same key (#"kCheckedBoxKey"), only one index will ever be stored, and it will always be the latest one that the user checked. All you would need to do the next time you load is ask userDefaults if it can find a value for the key #"kCheckedBoxKey", and if so, you would respond by programatically checking the index that was stored.
(you'd of course also want to clean it up by using #define CHECKED_KEY #"kCheckedBoxKey" at the top of the file, and use CHECKED_KEY instead of the literal string to protect against misspellings. At any rate, the point is to make sure you always save & restore using that same key.)
I recently had to save the state of each cell in my table view when the user selected or deselected them to add or remove checkmarks. Here is the snippet of code I used to save to a .plist file (let me know if you need the whole implementation I came up with:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *contentForThisRow = [[self list] objectAtIndex:[indexPath row]];
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%d%d", indexPath.section, indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSString *documentDirectory = [(AppDelegate *)[[UIApplication sharedApplication] delegate] applicationDocumentsDirectory];
NSString *PlistPath = [documentDirectory stringByAppendingPathComponent:#"Settings.plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:PlistPath];
NSString *row = [NSString stringWithFormat:#"%d",indexPath.row];
if([[dict objectForKey:row]isEqualToString:#"0"])
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
[[cell textLabel] setText:contentForThisRow];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *documentDirectory = [(AppDelegate *)[[UIApplication sharedApplication] delegate] applicationDocumentsDirectory];
NSString *PlistPath = [documentDirectory stringByAppendingPathComponent:#"Settings.plist"];
NSMutableDictionary *plist = [NSMutableDictionary dictionaryWithContentsOfFile:PlistPath];
UITableViewCell *cell = [self._tableView cellForRowAtIndexPath:indexPath];
NSString *row = [NSString stringWithFormat:#"%d",indexPath.row];
if(cell.accessoryType == UITableViewCellAccessoryNone)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
NSString *on = #"1";
[plist setObject:on forKey:row];
[plist writeToFile:PlistPath atomically:YES];
}
else if(cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
cell.accessoryType = UITableViewCellAccessoryNone;
NSString *off = #"0";
[plist setObject:off forKey:row];
[plist writeToFile:PlistPath atomically:YES];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
You only need to save the index of the selected row

Unrecognized selector sent. Objective-C error

I am writing a google reader application and have been trying to create the settings table view with UISwitch. Below is the complete code sequence:
#implementation Settings
#synthesize rowImage;
#synthesize ViewPushed;
#synthesize alreadySignedIn;
#synthesize syncStartupSwitch;
#synthesize confirmMarkSwitch;
#synthesize landscapeModeSwitch;
#synthesize appBadgeSwitch;
#synthesize fontSwitch;
#synthesize newItemsSwitch;
#pragma mark -
#pragma mark View lifecycle
static SEL syncStartup;
static SEL markAsReadConfirm;
static SEL landscapeMode;
static SEL appBadge;
static SEL fontSettings;
static SEL newItemsFirstSel;
+(void) initialize{
syncStartup = #selector(syncAtStartup:);
markAsReadConfirm = #selector (confirmMarkAsRead:);
landscapeMode = #selector (landscapeMode:);
appBadge = #selector (appBadgeSetting:);
fontSettings = #selector (largeFontSetting:);
newItemsFirstSel = #selector (newItemFirst:);
}
-(void) newItemFirst:(id)sender {
if ([sender isOn]) {
newItemsSwitch = YES;
}else {
newItemsSwitch = NO;
}
}
-(void) syncAtStartup:(id)sender {
if ([sender isOn]) {
syncStartupSwitch = YES;
}else {
syncStartupSwitch = NO;
}
}
-(void) confirmMarkAsRead:(id)sender{
if ([sender isOn]) {
confirmMarkSwitch = YES;
}else {
confirmMarkSwitch = NO;
[self.tableView reloadData];
}
}
-(void) landscapeMode:(id)sender{
if([sender isOn]) {
landscapeModeSwitch = YES;
}else {
landscapeModeSwitch = NO;
}
}
-(void) appBadgeSetting:(id)sender{
if([sender isOn]) {
appBadgeSwitch = YES;
}else {
appBadgeSwitch = NO;
}
}
-(void) largeFontSetting:(id)sender{
if ([sender isOn]) {
[UIFont systemFontOfSize:32];
fontSwitch = YES;
NSLog(#"YES");
}else {
fontSwitch = NO;
NSLog(#"YES");
}
}
/*
-(void) saveLastViewedItem{
[plistData setValue:[[[UIApplication sharedApplication]delegate]currentItemID]forKey:keyLastItemID];
[plistData setValue:[[[[[[[UIApplication sharedApplication]delegate]navController]navController]topViewController]delegate]tag]forKey:keyLastItemTag];
}
-(void) save {
[self saveLastViewedItem];
BOOL success = [plistData writeToFile:[docsPath stringByAppendingPathComponent:plistName] atomically:YES];
if (!success) {
NSLog(#"FAILED saving plist");
}else {
dbg_s(#"saved data:%# to file: %#", plistData, [docsPath stringByAppendingPathComponent:plistName]);
}
}
-(void) load{
dbg(#"loading plist data from path: %#", [docsPath stringByAppendingPathComponent:plistName]);
plistData = [[NSMutableDictionary dictionaryWithContentsOfFile:[docsPath stringByAppendingPathComponent:plistName]]retain];
if(!plistData){
NSLog(#"FAILED loading plist");
plistData = [[NSMutableDictionary dictionary] retain];
}
dbg_s(#"Loaded plist data", plistData);
dbg_s("%#", plistData);
[self removeDeprecatedProperties];
[self loadFeedList];
}
-(void) removeDeprecatedProperties{
for (NSString * deprecatedProperty in deprecatedProperties){
[plistData removeObjectForKey:deprecatedProperty];
}
}
-(void) reloadFeedList{
[self loadFeedList];
[self setUIElements];
}
-(NSArray *) loadFeedList {
NSString *contents = [NSString stringWithContentsOfFile:[docsPath stringByAppendingPathComponent:#"tagList"]encoding:NSUTF8StringEncoding error:nil];
id result;
if(!contents) {
dbg(#"no feed list loaded");
result = nil;
}else {
NSArray *originalList = [contents componentsSeparatedByString:#"\n"];
NSMutableArray *feedList = [NSMutableArray arrayWithCapacity:[originalList count]];
for (NSString *feed in originalList) {
NSString *trimmedFeed = [feed stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if([feed length] > 0){
[feedList addObject:trimmedFeed];
}
}
result = feedList;
}
[possibleTags release];
possibleTags = [result retain];
return result;
}
-(NSArray *)feedList {
return possibleTags;
}
-(NSArray *) activeTagList {
id tags = [self tagList];
NSArray *result = [NSMutableArray arrayWithCapacity:[tags count]];
for (NSString *tag in tags) {
if([possibleTags containsObject:tag]) {
[result arrayByAddingObject:tag];
}
}
return result;
}
-(id) init{
self =[super init];
plistName = #"config.plist";
if (openLinksInSegmentValues == nil)
openLinksInSegmentValues = [[NSArray alloc] initWithObjects:openLinksInAskMeValue, openLinksInSafariValue, openLinksIniReaderValue, nil];
if (deprecatedProperties == nil)
deprecatedProperties = [[NSArray alloc] initWithObjects:#"openInSafari", nil];
[self docsPath];
[self load];
return self;
}
*/
- (void)viewDidLoad {
syncSwitch=[[[UISwitch alloc] initWithFrame:CGRectZero]autorelease];
readSwitch=[[[UISwitch alloc] initWithFrame:CGRectZero]autorelease];
landscapeSwitch=[[[UISwitch alloc] initWithFrame:CGRectZero]autorelease];
badgeSwitch=[[[UISwitch alloc] initWithFrame:CGRectZero]autorelease];
largeFontSwitch=[[[UISwitch alloc] initWithFrame:CGRectZero]autorelease];
newItemsFirstSwitch =[[[UISwitch alloc] initWithFrame:CGRectZero]autorelease];
//switcher = [[[UISwitch alloc] initWithFrame:CGRectZero]autorelease];
NSString *loginData;
NSError *keychainError;
NSString *checkUsername= [SFHFKeychainUtils getPasswordForUsername:#"Username" andServiceName:#"iReader" error:&keychainError];
NSString *checkPassword = [SFHFKeychainUtils getPasswordForUsername:#"Password" andServiceName:#"iReader" error:&keychainError];
if (checkPassword == nil || checkUsername == nil) {
alreadySignedIn = NO;
loginData = #"Sync Settings";
} else {
alreadySignedIn = YES;
loginData = #"Logout";
}
if(ViewPushed == NO) {
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
target:self action:#selector(cancel_Clicked:)] autorelease];
}
listOfItems = [[NSMutableArray alloc] init];
NSArray *syncSettingsToLoad = [NSArray arrayWithObjects:loginData, nil];
NSDictionary *syncSettingsToLoadDict = [NSDictionary dictionaryWithObject:syncSettingsToLoad forKey:#"Settings"];
NSArray *generalSetting = nil;
generalSetting = [NSArray arrayWithObjects:#"Sync at Startup",#"Confirm Mark as Read", #"Landscape Mode", #"Cache Settings",nil];
NSMutableDictionary *generalSettingsDict = [NSMutableDictionary dictionaryWithObject:generalSetting forKey:#"Settings"];
NSArray *appearanceSettings = [NSArray arrayWithObjects:#"New Items First", #"App Icon Badge", #"Large Font", nil];
NSDictionary *appearanceSettingsDict = [NSDictionary dictionaryWithObject:appearanceSettings forKey:#"Settings"];
NSArray *sharingSettings = [NSArray arrayWithObjects:#"Customize Sharing Options", nil];
NSDictionary *sharingSettingsDict = [NSDictionary dictionaryWithObject:sharingSettings forKey:#"Settings"];
NSArray *advancedSettings = [NSArray arrayWithObjects:#"Advanced Options", nil];
NSDictionary *advancedSettingsDict = [NSDictionary dictionaryWithObject:advancedSettings forKey:#"Settings"];
[listOfItems addObject:syncSettingsToLoadDict];
[listOfItems addObject:generalSettingsDict];
[listOfItems addObject:appearanceSettingsDict];
[listOfItems addObject:sharingSettingsDict];
[listOfItems addObject:advancedSettingsDict];
self.title =#"Settings";
// Uncomment the following line to preserve selection between presentations.
//self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
[super viewDidLoad];
}
//defaultDatabase = [[userPrefs valueForKey:MAPref_DefaultDatabase] retain];
-(void) cancel_Clicked:(id)sender
{
[self.navigationController dismissModalViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated {
//[self.navigationController setNavigationBarHidden:YES animated:animated];
[super viewWillAppear:animated];
}
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return [listOfItems count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
NSDictionary *dictionary = [listOfItems objectAtIndex:section];
NSArray *array = [dictionary objectForKey:#"Settings"];
return [array count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:
(NSInteger) section {
if (section == 0) {
return #"Sync Settings";
}
if (section == 1) {
return #"General Options";
}
if (section == 2) {
return #"Appearance Options";
}
if (section == 3){
return #"Sharing Options";
}
if (section == 4){
return #"Advanced Options";
}
return nil;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//NSLog(#"This is what we are looking for %# %#", checkUsername, checkPassword);
// Configure the cell...
NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
NSArray *array =[dictionary objectForKey:#"Settings"];
NSString * cellValue = [array objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (indexPath.section == 0 && indexPath.row == 0) {
static NSString *SomeIdentifierA = #"SomeIdentifierA";
// This could be some custom table cell class if appropriate
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SomeIdentifierA];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierA] autorelease];
cell.accessoryType = UITableViewCellSelectionStyleBlue;
}
cell.textLabel.text =cellValue;
return cell;
}
else if (indexPath.section ==1 && indexPath.row ==0) {
static NSString *SomeIdentifierB = #"SomeIdentifierB";
// This could be some custom table cell class if appropriate
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SomeIdentifierB];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierB] autorelease];
[syncSwitch addTarget:self action:#selector(syncAtStartup:) forControlEvents:UIControlEventValueChanged];
//[cell.contentView addSubview:syncSwitch];
cell.accessoryView = syncSwitch;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
//cell.reuseIdentifier = #"Cell1";
}
cell.textLabel.text =#"Sync at Startup";
return cell;
}
else if(indexPath.section == 1 && indexPath.row == 1){
static NSString *SomeIdentifierC = #"SomeIdentifierC";
// This could be some custom table cell class if appropriate
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SomeIdentifierC];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierC] autorelease];
[readSwitch addTarget:self action:#selector(confirmMarkAsRead:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = readSwitch;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text =#"Confirm Mark as Read";
return cell;
}
else if(indexPath.section == 1 && indexPath.row == 2){
static NSString *SomeIdentifierD = #"SomeIdentifierD";
// This could be some custom table cell class if appropriate
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SomeIdentifierD];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierD] autorelease];
[landscapeSwitch addTarget:self action:#selector(landscapeMode:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = landscapeSwitch;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text =#"Landscape Mode";
return cell;
}
else if (indexPath.section == 1 && indexPath.row == 3) {
static NSString *SomeIdentifierE = #"SomeIdentifierE";
// This could be some custom table cell class if appropriate
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SomeIdentifierE];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierE] autorelease];
cell.accessoryType = UITableViewCellSelectionStyleBlue;
}
cell.textLabel.text =#"Cache Settings";
return cell;
}
else if (indexPath.section == 1 && indexPath.row == 4) {
static NSString *SomeIdentifierJ = #"SomeIdentifierJ";
// This could be some custom table cell class if appropriate
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SomeIdentifierJ];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierJ] autorelease];
cell.accessoryType = UITableViewCellSelectionStyleBlue;
}
cell.textLabel.text =#"Caches";
return cell;
}
else if(indexPath.section == 2 && indexPath.row == 0){
static NSString *SomeIdentifierN = #"SomeIdentifierF";
// This could be some custom table cell class if appropriate
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SomeIdentifierN];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierN] autorelease];
[newItemsFirstSwitch addTarget:self action:#selector(newItemFirst:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = newItemsFirstSwitch;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text =#"App Icon Badge";
return cell;
}
else if(indexPath.section == 2 && indexPath.row == 1){
static NSString *SomeIdentifierF = #"SomeIdentifierF";
// This could be some custom table cell class if appropriate
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SomeIdentifierF];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierF] autorelease];
[badgeSwitch addTarget:self action:#selector(appBadgeSetting:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = badgeSwitch;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text =#"App Icon Badge";
return cell;
}
else if(indexPath.section == 2 && indexPath.row == 2){
static NSString *SomeIdentifierG = #"SomeIdentifierG";
// This could be some custom table cell class if appropriate
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SomeIdentifierG];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierG] autorelease];
[largeFontSwitch addTarget:self action:#selector (largeFontSetting:) forControlEvents:UIControlEventValueChanged];
//[largeFontSwitch addTarget:self action:#selector(largeFontSetting:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = largeFontSwitch;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
cell.textLabel.text =#"Large Font Size";
return cell;
}
else if (indexPath.section == 3 && indexPath.row == 0) {
static NSString *SomeIdentifierH = #"SomeIdentifierH";
// This could be some custom table cell class if appropriate
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SomeIdentifierH];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierH] autorelease];
cell.accessoryType = UITableViewCellSelectionStyleBlue;
}
cell.textLabel.text =#"Customize Sharing Options";
return cell;
}
else if (indexPath.section == 4 && indexPath.row == 0) {
static NSString *SomeIdentifierI = #"SomeIdentifierI";
// This could be some custom table cell class if appropriate
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SomeIdentifierI];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:SomeIdentifierI] autorelease];
cell.accessoryType = UITableViewCellSelectionStyleBlue;
}
cell.textLabel.text =#"Advanced Options";
return cell;
}
//switcher.on = [[NSUserDefaults standardUserDefaults]boolForKey:#"Settings"];
cell.textLabel.font = [UIFont boldSystemFontOfSize:13];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section ==0){
if (alreadySignedIn == NO) {
if(indexPath.section == 0 && ivControllerCell == nil ){
[tableView reloadData];
ivControllerCell = [[GoogleClientLogin alloc] initWithNibName:#"GoogleClientLogin" bundle:[NSBundle mainBundle]];
ivControllerCell.ViewPushed = YES;
//Push the view controller to the top of the stack.
[self.navigationController pushViewController:ivControllerCell animated:YES];
[ivControllerCell release];
ivControllerCell = nil;
}
}
if (alreadySignedIn ==YES) {
NSError *keyChainEmpty;
[SFHFKeychainUtils deleteItemForUsername:#"Username" andServiceName:#"iReader" error:&keyChainEmpty];
[SFHFKeychainUtils deleteItemForUsername:#"Password" andServiceName:#"iReader" error:&keyChainEmpty];
ivControllerCell = [[GoogleClientLogin alloc] initWithNibName:#"GoogleClientLogin" bundle:[NSBundle mainBundle]];
ivControllerCell.ViewPushed = YES;
[self.navigationController pushViewController:ivControllerCell animated:YES];
}
}
}
-(void) removeSelfFromWindow
{/*
if(self.view.superview){
[UIView beginAnimations:#"curldown" context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:0.5];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:NO];
[self.view.superview removeFromSuperview];
}
[UIView commitAnimations];
*/}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
/*static Settings * _standardSettings = nil;
+(Settings *)standardSettings
{
if (_standardSettings == nil)
_standardSettings = [[Settings alloc] init];
return _standardSettings;
}*/
-(void) setUIElements {
[landscapeSwitch setOn:[self landscapeModeSwitch]];
//[feedList setSelectedFeeds:[self taglist]];
}
- (void)dealloc {
[self save];
[plistData release];
[plistName release];
[super dealloc];
}
#end
I am getting the following error when I start scrolling the table view.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType addTarget:action:forControlEvents:]: unrecognized selector sent to instance 0x5f463e0'
Can somebody please help me with this error?
Cheers
Don't autorelease the switches when you alloc them. After those lines you don't own any of those objects.
syncSwitch=[[UISwitch alloc] initWithFrame:CGRectZero];
Release them in the dealloc method
[syncSwitch release];

Resources