NSUser Defaults save button status and display again - iphone

I am new to iphone development. I am developing an app in that i am displaying some contact name with uncheckmark image. Once user taps the button to selected means i am storing it in an nsuserdefaults. Here is the code what i have tried.Actually my problem is another user value will change dynamically.I am adding one boolean value for all the users who are coming in the tableview. If an one more person is added in the another user i want to show in off state. For other users i have to store the values stored in nsuserdefaults. First time i am manually looping 0 in total user.
My interface File
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
NSArray * test;
IBOutlet UITableViewCell *customCell;
IBOutlet UIImageView *photo;
IBOutlet UILabel *userName;
NSMutableArray *dataArray;
NSMutableDictionary *tempDictionary;
NSMutableArray * selected;
NSUserDefaults *prefs;
NSMutableArray * statusArray;
NSMutableArray * prefsArray;
}
#property(nonatomic,retain) IBOutlet UITableViewCell *customCell;
#property(nonatomic,retain)IBOutlet UITableView *tblView;
#property(nonatomic,retain) NSMutableArray *dataArray;
#end
implementation file:
- (void)viewDidLoad
{
dataArray=[[NSMutableArray alloc]init];
selected=[[NSMutableArray alloc]init];
prefs=[NSUserDefaults standardUserDefaults];
prefsArray=[[NSMutableArray alloc]init];
NSMutableArray * anotheruser=[NSMutableArray arrayWithObjects:#"da",#"kn",#"gn",#"Prd",#"Kai",#"Sh",nil];
for (int i=0; i<anotheruser.count;i++) {
[selected addObject:[NSNumber numberWithInt:0]];
}
for (int i=0; i< anotheruser.count; i++) {
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:[anotheruser objectAtIndex:i] forKey:#"name"];
[dict setValue:[selected objectAtIndex:i] forKey:#"checked"];
[self.dataArray addObject:dict];
}
[super viewDidLoad];
}
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:NSInteger)section
{
return dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"MyViewCell" owner:self options:nil];
cell = customCell;
self.customCell = nil;
}
photo.image=[UIImage imageNamed:#"raj.jpg"];
NSMutableDictionary *item = [self.dataArray objectAtIndex:indexPath.row];
userName.text= [item objectForKey:#"name"];
[item setObject:cell forKey:#"cell"];
BOOL checked = [[item objectForKey:#"checked"] boolValue];
UIImage *image = (checked) ? [UIImage imageNamed:#"checked.png"] : [UIImage imageNamed:#"unchecked.png"];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
button.frame = frame; // match the button's size with the image size
[button setBackgroundImage:image forState:UIControlStateNormal];
[button addTarget:self action:#selector(checkButtonTapped:event:) forControlEvents:UIControlEventTouchUpInside];
cell.backgroundColor = [UIColor clearColor];
cell.accessoryView = button;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self tableView: tblView accessoryButtonTappedForRowWithIndexPath: indexPath];
[self.tblView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)checkButtonTapped:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:tblView];
NSIndexPath *indexPath = [tblView indexPathForRowAtPoint: currentTouchPosition];
if (indexPath != nil)
{
[self tableView:tblView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath: (NSIndexPath *)indexPath
{
NSMutableDictionary *item = [dataArray objectAtIndex:indexPath.row];
BOOL checked = [[item objectForKey:#"checked"] boolValue];
NSUInteger myInt=indexPath.row;
[item setObject:[NSNumber numberWithBool:!checked] forKey:#"checked"];
UITableViewCell *cell = [item objectForKey:#"cell"];
UIButton *button = (UIButton *)cell.accessoryView;
if (!checked)
{
[selected replaceObjectAtIndex:myInt withObject:[NSNumber numberWithInt:1]];
}else{
[selected replaceObjectAtIndex:myInt withObject:[NSNumber numberWithInt:0]];
}
[prefs setObject:selected forKey:#"status"];
NSLog(#"%#", selected);
UIImage *newImage = (checked) ? [UIImage imageNamed:#"unchecked.png"] : [UIImage imageNamed:#"checked.png"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
}

Just try with this code in cellForRowAtIndexPath: method
For CustomCell use like below..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyViewCell *cell = (MyViewCell *) [tableView dequeueReusableCellWithIdentifier:nil];
// MyCustomeCell *cell = (MyCustomeCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];//custom cell
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"MyViewCell" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (MyViewCell *) currentObject;
break;
}
}
}
and for DefaultCell use bellow code...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *kCustomCellID = #"MyCellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle=UITableViewCellSelectionStyleBlue;
}
}

Related

UITableView Crashes when scrolling and [reloadData]

I'm creating a app using theos (jailbreak) and I have created a UITableView in the loadView method in my RootViewController.mm file:
- (void)loadView {
self.view = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
self.view.backgroundColor = [UIColor redColor];
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:#"/var/mobile/Library/BannerImage" error:&error];
countries = [NSDictionary dictionaryWithObject:directoryContents forKey:#"Themes"];
mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStyleGrouped];
[mainTableView setDataSource:self];
[mainTableView setDelegate:self];
[self.view addSubview:mainTableView];
}
And the rest of my code:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [countries count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [[countries allKeys] objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSString *continent = [self tableView:tableView titleForHeaderInSection:section];
return [[countries valueForKey:continent] count];
}
- (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];
}
// Configure the cell...
NSString *continent = [self tableView:tableView titleForHeaderInSection:indexPath.section];
NSString *country = [[countries valueForKey:continent] objectAtIndex:indexPath.row];
cell.textLabel.text = country;
cell.accessoryType = UITableViewCellAccessoryNone;
if([self.checkedIndexPath isEqual:indexPath])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *object = [tableView cellForRowAtIndexPath:indexPath];
[object setSelected:NO animated:YES];
NSString *selectedTheme = [[object textLabel] text];
NSDictionary *plistFile = [NSDictionary dictionaryWithObject:selectedTheme forKey:#"CurrentTheme"];
[plistFile writeToFile:#"/Applications/BannerImage.app/CurrentTheme.plist" atomically:YES];
if(self.checkedIndexPath)
{
UITableViewCell* uncheckCell = [tableView
cellForRowAtIndexPath:checkedIndexPath];
uncheckCell.accessoryType = UITableViewCellAccessoryNone;
}
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
self.checkedIndexPath = indexPath;
}
It crashes when I scroll up and try to scroll back down and it crashes when [mainTableView reloadData] is called. How can I fix this?
Crash Log
I found out that I needed to retain the Dictionary because it was being released. So instead of
NSDictionary *countries;
change to this
#property(nonatomic, retain) NSDictionary *countries;
and
#synthesize countries;
in your .mm file and use
self.countries = [NSDictionary dictionaryWithObject:directoryContents forKey:#"Themes"];
instead of
countries = [NSDictionary dictionaryWithObject:directoryContents forKey:#"Themes"];
Hi, Please check there if is any data in countries and "continent" value key is presented or not in dic before this line
NSString *country = [[countries valueForKey:continent] objectAtIndex:indexPath.row];

Checkmarks single selection

I'm currently developing a UITableView with items for selection with check marks.
The problem is I need to put a restriction on how many items are selected at a single time.
For Example:
NO onions, NO salt, YES milk, NO oranges.
As this example shows, I need a restriction so that the user can only select one item.
Current Code:
-(void)checkButtonPressed:(id)sender event:(id)event {
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.myTableView];
indexP = [self.myTableView indexPathForRowAtPoint: currentTouchPosition];
NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
//MasterCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"MasterCell"];
item = [arrayData objectAtIndex:indexP.row];
if (indexP != nil) {
[self tableView: self.myTableView accessoryButtonTappedForRowWithIndexPath:indexP];
}
[self.myTableView reloadData];
}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
NSMutableDictionary *item = [arrayData objectAtIndex:indexPath.row];
BOOL checked = [[item objectForKey:#"checked"] boolValue];
[item setObject:[NSNumber numberWithBool:!checked] forKey:#"checked"];
UITableViewCell *cell = [item objectForKey:#"cell"];
UIButton *button = (UIButton *)cell.accessoryView;
UIImage *newImage = (checked) ? [UIImage imageNamed:#"unchecked.png"] : [UIImage imageNamed:#"checked.png"];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
NSLog(#"accessoryButtonTappedForRowWithIndexPath____");
}
My cellForRowAtIndexPath:
- (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];
}
NSMutableDictionary *item = [arrayData objectAtIndex:indexPath.row];
UILabel *nomeLabel = (UILabel *)[cell viewWithTag:2];
UIButton *btnCheck = (UIButton *)[cell viewWithTag:3];
BOOL checked = [[item objectForKey:#"checked"] boolValue];
UIImage *image = (checked) ? [UIImage imageNamed:#"checked.png"] : [UIImage imageNamed:#"unchecked.png"];
[btnCheck setBackgroundImage:image forState:UIControlStateNormal];
nomeLabel.text = [item valueForKey:#"nome"];
nomeLabel.textColor = [UIColor blackColor];
[btnCheck addTarget:self action:#selector(checkButtonPressed:event:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}
Thanks in advance and sorry for my bad English, please don't down vote, just ask if you have any doubt I'm always around to answer.
Try this ::
.h File,
#property(nonatomic, retain) NSIndexPath *lastIndexPath;
.m File,
int oldRow, newRow;
Table Methods:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CustomCellIdentifier = #"customCell";
customCell *cell = (customCell *)[tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];
if (cell == nil)
{
NSArray *nib;
nib= [[NSBundle mainBundle] loadNibNamed:#"customCell" owner:self options:nil];
for (id oneObject in nib)
if ([oneObject isKindOfClass:[customCell class]])
cell = (customCell *)oneObject;
newRow = [indexPath row];
oldRow = [[self lastIndexPath] row];
cell.accessibilityViewIsModal = (newRow == oldRow && lastIndexPath != nil) ? NO : YES;
if(cell.accessibilityViewIsModal == NO)
cell.imgCheck.image = [UIImage imageNamed:#"Checkbox_Checked_New.png"];
else
cell.imgCheck.image = [UIImage imageNamed:#"Checkbox_Unchecked_New.png"];
return cell;
}
}
DidSelect ::
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
newRow = [indexPath row];
oldRow = [[self lastIndexPath] row];
//Check Mark Feature
if (newRow != oldRow)
{
customCell *newCell = (customCell *)[tableView cellForRowAtIndexPath:indexPath];
newCell.imgCheck.image = [UIImage imageNamed:#"Checkbox_Checked_New.png"];
customCell *oldCell = (customCell *)[tableView cellForRowAtIndexPath:lastIndexPath];
oldCell.imgCheck.image = [UIImage imageNamed:#"Checkbox_Unchecked_New.png"];
[self setLastIndexPath:indexPath];
}
else
{
customCell *newCell = (customCell *)[tableView cellForRowAtIndexPath:indexPath];
newCell.imgCheck.image = [UIImage imageNamed:#"Checkbox_Checked_New.png"];
[self setLastIndexPath:indexPath];
}
}
Basically, for this kind of business logic, you're going to have to code it yourself. When using table views as what are basically radio buttons, the only way to enforce the requirement of single selection is to write code that handles the situation of the user trying to select the second item in the manner that your system will require:
Allow multiple selections (not the case here, but in some cases you might)
Remove all other checks that are incompatible with this, check the selected item, and tell the table view to refresh all of the rows you just changed
Present an error to the user in some fashion (blink, alert, sound) – almost never a good idea when you can allow direct manipulation.
try like this may be it helps you, here lastIndexPath is an NSIndexPath variable declared in .h file.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell* Cell = [tableView cellForRowAtIndexPath:indexPath];
int new = [indexPath row];
int old = (lastIndexPath != nil) ? [lastIndexPath row] : -1;
if(new != old)
{
Cell.accessoryType = UITableViewCellAccessoryCheckmark;
UITableViewCell* oldCell = [tableView cellForRowAtIndexPath:lastIndexPath];
oldCell.accessoryType = UITableViewCellAccessoryNone;
lastIndexPath = indexPath;
}
}

How to keep the checkmark in a UITableView after the view disappears

I have a uitableview that's displaying multiple selections with a custom checkmark. When selected the rows value is save using NSUserDefaults. The problem is that despite the values being saved the checkmarks disappear from the table cell rows. I can't figure out why.
thanks for any help, I'm really stuck on this.
Here's the .h code:
#interface CategoriesViewController : UITableViewController {
NSString *selectedCategoryTableString;
NSString *jsonStringCategory;
int prev;
}
// arForTable array will hold the JSON results from the api
#property (nonatomic, retain) NSArray *arForTable;
#property (nonatomic, retain) NSMutableArray *arForIPs;
#property (nonatomic, retain) NSMutableArray *categorySelected;
#property (nonatomic, retain) NSString *jsonStringCategory;
#property(nonatomic, retain) UIView *accessoryView;
#end
and the .m code:
#implementation CategoriesViewController
#synthesize jsonStringCategory;
#synthesize arForTable = _arForTable;
#synthesize arForIPs = _arForIPs;
- (void)viewDidLoad
{
[super viewDidLoad];
self.arForIPs=[NSMutableArray array];
self.categorySelected = [[NSMutableArray alloc] init];
[self reloadMain];
self.tableView.allowsMultipleSelection = YES;
}
-(void) reloadMain {
jsonString = #"http:///******";
// Download the JSON
NSString *jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:jsonString]
encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
NSMutableArray *itemsTMP = [[NSMutableArray alloc] init];
// Create parser
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
itemsTMP = [results objectForKey:#"results"];
self.arForTable = [itemsTMP copy];
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.arForTable count];
}
- (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];
[cell.textLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
[cell.detailTextLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
cell.accessoryView.hidden = NO;
}
UIImageView *cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon-tick.png"]] ;
UIImageView *cellAccessoryNoneImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#""]] ;
if([self.arForIPs containsObject:indexPath]){
cell.accessoryView = cellAccessoryImageView;
} else {
cell.accessoryView = cellAccessoryNoneImageView;
}
// Get item from tableData
NSDictionary *item = (NSDictionary *)[_arForTable objectAtIndex:indexPath.row];
// encoding fix
NSString *utf8StringTitle = [item objectForKey:#"name"];
NSString *correctStringTitle = [NSString stringWithCString:[utf8StringTitle cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];
cell.textLabel.text = [correctStringTitle capitalizedString];
NSNumber *num = [item objectForKey:#"id"];
cell.detailTextLabel.text = [num stringValue];
cell.detailTextLabel.hidden = YES;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if([self.arForIPs containsObject:indexPath]){
[self.arForIPs removeObject:indexPath];
[self.categorySelected removeObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:#"id"]];
} else {
[self.arForIPs addObject:indexPath];
[self.categorySelected addObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:#"id"]];
NSLog(#"%# categorySelected",self.categorySelected);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSLog(#"%# defaults categorySelected",[defaults arrayForKey:#"selectedCategoryTableString"]);
NSString *string = [self.categorySelected componentsJoinedByString:#","];
[defaults setObject:string forKey:#"selectedCategoryTableString"];
NSLog(#"%# STRING",string);
}
[tableView reloadData];
}
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:NO];
[self.navigationController setNavigationBarHidden:YES animated:NO];
self.navigationController.toolbarHidden = YES;
}
First of all your code has lots of memory leaks, please do use the static analyzer and/or instruments to fix them, few for them are pretty obvious like you initialized the SBJSON parser and did not release it, itemsTMP is another.
I have rewritten your code to be much more efficient and memory friendly:
#interface CategoriesViewController : UITableViewController
{
NSArray *_items;
NSMutableArray *_selectedItems;
UIImageView *cellAccessoryImageView;
}
#end
#implementation CategoriesViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_selectedItems = [NSMutableArray new];
cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon-tick.png"]] ;
[self reloadMain];
self.tableView.allowsMultipleSelection = YES;
}
- (void)reloadMain
{
NSString *jsonString = #"http:///******";
// Download the JSON
jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:jsonString]
encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
// Create parser
SBJSON *parser = [SBJSON new];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
if (_items) [_items release];
_items = [[results objectForKey:#"results"] copy];
[parser release];
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_items count];
}
- (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] autorelease];
[cell.textLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
[cell.detailTextLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
cell.accessoryView.hidden = NO;
}
NSDictionary *item = [_items objectAtIndex:indexPath.row];
if ([_selectedItems containsObject:item])
{
// preloaded image will help you have smoother scrolling
cell.accessoryView = cellAccessoryImageView;
}
else
{
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryNone;
}
// Get item from tableData
cell.textLabel.text = [[NSString stringWithCString:[[item objectForKey:#"name"] cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding] capitalizedString];
cell.detailTextLabel.text = [[item objectForKey:#"id"] stringValue];
cell.detailTextLabel.hidden = YES;
item = nil;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *item = [_items objectAtIndex:indexPath.row];
if ([_selectedItems containsObject:item])
{
[_selectedItems removeObject:item];
}
else
{
[_selectedItems addObject:item];
}
item = nil;
[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (void)dealloc
{
[_selectedItems release];
[cellAccessoryImageView release];
[super dealloc];
}
#end
Since in your table there is only one section. Try this approach and this will help you certainly.
In - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath write following code;
if([self.arForIPs containsObject:[NSNumber numberWithInt:indexPath.row]]){
cell.accessoryView = cellAccessoryImageView;
} else {
cell.accessoryView = cellAccessoryNoneImageView;
}
And in - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath write code as below,
if([self.arForIPs containsObject:[NSNumber numberWithInt:indexPath.row]]){
[self.arForIPs removeObject:[NSNumber numberWithInt:indexPath.row]];
} else {
[self.arForIPs addObject:[NSNumber numberWithInt:indexPath.row]]
}

CheckBox Item in Custom Designed UITableViewCell , IPhone SDK

I have designed a custom table cell. which displays product information.
When i implement CellForRowAtIndexPath I am doing this.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *sectionTableCellIdentifier = [[NSString alloc] initWithFormat:#"GLItemTableCellIdentifierNumber%d",indexPath.section];
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"GLItemDetailsTableCellIdentifier"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:sectionTableCellIdentifier];
if (cell == nil)
{
NSDictionary *dict = [self.listData objectAtIndex:indexPath.row];
ItemsListTableCell *cell = (ItemsListTableCell *)[tableView dequeueReusableCellWithIdentifier:sectionTableCellIdentifier];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ItemsListTableCell"
owner:self options:nil];
for (id oneObject in nib)
{
if ([oneObject isKindOfClass:[ItemsListTableCell class]])
{
cell = (ItemsListTableCell *)oneObject;
}
}
NSString *priceinfo = [[NSString alloc] initWithFormat:#"$%#",[dict objectForKey:#"CurrentPrice"]];
NSString *sizeinfo = [[NSString alloc] initWithFormat:#"Size: %#",[dict objectForKey:#"Size"]];
NSString *upcInfo = [[NSString alloc] initWithFormat:#"UPC: %#",[dict objectForKey:#"ID"]];
NSString *strQuantity = [[NSString alloc] initWithFormat:#"%#",[dict objectForKey:#"Quantity"]];
cell.lblProductName.text = [dict objectForKey:#"Name"];
cell.lblSize.text = sizeinfo;
cell.lblBrand.text = [dict objectForKey:#"BrandName"];
cell.lblProductCode.text = upcInfo;
cell.lblQuantity.text = strQuantity;
cell.lblPrice.text = priceinfo;
cell.lblStoreName.text = [dict objectForKey:#"StoreName"];
cell.isSelected = NO;
[cell.btnSelected addTarget:self action:#selector(cellButtonTapped:)
forControlEvents:UIControlEventTouchUpInside];
[upcInfo release];
[priceinfo release];
[strQuantity release];
[sizeinfo release];
return cell;
}
return cell;
}
now for the click event I am doing
- (IBAction)cellButtonTapped:(id)sender
{
UIView *contentView = [sender superview];
ItemsListTableCell *cell = (ItemsListTableCell *)[contentView superview];
NSIndexPath *indexPath = [table indexPathForCell:cell];
NSUInteger buttonRow = [[self.table
indexPathForCell:cell] row];
NSUInteger buttonSection = [[self.table
indexPathForCell:cell] section];
NSLog(#"Index Path Row : %d",buttonRow);
NSLog(#"Index Path Section : %d",buttonSection);
ItemsListTableCell *buttonCell =
(ItemsListTableCell *)[table cellForRowAtIndexPath:indexPath];
if (buttonCell.isSelected == YES)
{
buttonCell.isSelected = NO;
UIImage *image = [[UIImage imageNamed:#"checkbox-empty.png"] autorelease];
[buttonCell.btnSelected setImage:image forState:UIControlStateNormal];
}
else
{
buttonCell.isSelected = YES;
UIImage *image = [[UIImage imageNamed:#"checkbox-full.png"] autorelease];
[buttonCell.btnSelected setImage:image forState:UIControlStateNormal];
}
self.txtQuantity.text = buttonCell.lblQuantity.text;
NSString *buttonTitle = buttonCell.lblProductName.text;
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"You tapped the button"
message:[NSString stringWithFormat:
#"You tapped the button for %#", buttonTitle]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
The Problem is when i click on check button it is going to the event. but I am unable to detect what is the parent cell . as there are some values in cell.
Instead of creating such an event (IBAction), you could do all of these in
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
if (selectedCell.accessoryType == UITableViewCellAccessoryNone)
{
selectedCell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
if (selectedCell.accessoryType == UITableViewCellAccessoryCheckmark)
{
selectedCell.accessoryType = UITableViewCellAccessoryNone;
}
}
If you want a checkmark of your own style, you could set them up here and finish off things. Makes stuff easier !

heightForRowAtIndexPath crashes

I have the following code:
- (CGFloat)tableView:(UITableView *) tableView heightForRowAtIndexPath:(NSIndexPath *) indexPath{
TestCell* cell = (ConvoreCell *) [tableView cellForRowAtIndexPath:indexPath];
CGSize textSize = [[cell text] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake([tableView frame].size.width - 20, 500)];
return 80;
}
It crashes on the cellForRowAtIndexPath, why is this? The log doesn't tell me anything. Here's my cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"ConvoreCell";
AsyncImageView *asyncImageView = nil;
TestCell * cell = (TestCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"TestCell" owner:nil options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (ConvoreCell *) currentObject;
break;
}
}
asyncImageView = [[[AsyncImageView alloc] init] autorelease];
asyncImageView.imageview = cell.icon;
}
else {
asyncImageView = (AsyncImageView *) [cell.contentView viewWithTag:ASYNC_IMAGE_TAG];
}
NSMutableDictionary *cellValue = [results objectAtIndex:indexPath.row];
NSString *picURL = [[cellValue objectForKey:#"user"] objectForKey:#"img"];
if ([picURL isEqualToString:#"https://secure.gravatar.com/avatar/1f043010eb1652b3fab3678167dc0487/?default=https%3A%2F%2Fconvore.com%2Fmedia%2Fimages%2Feric.png&s=80"])
picURL = #"https://test.com/media/images/eric.png";
[asyncImageView loadImageFromURL:[NSURL URLWithString:picURL]];
cell.title.text = [cellValue objectForKey:#"message"];
cell.info.text = [NSString stringWithFormat:#"%# %# days ago", [[cellValue objectForKey:#"user"] objectForKey:#"username"], [cellValue objectForKey:#"date_created"] ];
return cell;
}
All I want to do is to resize the height of the cell according to the cell.title.text....
It's wrong to call cellForRowAtIndexPath: manually. You have to store those strings separately in array and obtain them from there.
A rule of thumb: don't call framework callbacks manually.