Checkmarks single selection - iphone

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;
}
}

Related

custom label value is disappearing when scrolling table view

I am new to iphone. my cutomcell label value is disappearing when I scroll the table view.
Again it appears when I click on that cell.
Can anyone help me?
Thanks in Advance.
//table view in view controller created in xib
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ListOfProductsCell";
ListOfProductsCell *cell = (ListOfProductsCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
NSArray *nib =[[NSBundle mainBundle] loadNibNamed:#"ListOfProductsCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
productItemDit=[productListArry objectAtIndex:indexPath.row];
NSString *offerStr= [NSString stringWithFormat:#"%.2f",[[productItemDit objectForKey:#"offer"] floatValue]];
NSString *fullCostStr=[[currencyCodeStr stringByAppendingString:#" "] stringByAppendingString:offerStr];
NSLog(#"%#",fullCostStr);
cell.itemCostLbl.text=fullCostStr;
} else {
cell.itemStepper = (UIStepper *) [cell viewWithTag:2];
cell.itemAddedLbl =(UILabel*)[cell viewWithTag:1];
}
if (tableView == self.searchDisplayProduct.searchResultsTableView) {
searchProductItemDit=[searchProductListArry objectAtIndex:indexPath.row];
NSLog(#"searchdit:%#",searchProductItemDit);
cell.itemNameLbl.text= [searchProductItemDit objectForKey:#"name"];
self.searchDisplayProduct.searchResultsTableView.separatorColor=[UIColor colorWithRed:200.0 green:0.0 blue:0.0 alpha:1.0];
} else {
productItemDit=[productListArry objectAtIndex:indexPath.row];
NSLog(#"dit:%#",productItemDit);
cell.itemNameLbl.text=[productItemDit objectForKey:#"name"];
}
cell.itemAddedLbl.text = [[NSString alloc] initWithFormat:#"%d",itemCount];
cell.itemImg.image = [UIImage imageNamed:#"profp.jpg"];
return cell;
}
Solved by doing like this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ListOfProductsCell";
ListOfProductsCell *cell = (ListOfProductsCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
NSArray *nib =[[NSBundle mainBundle] loadNibNamed:#"ListOfProductsCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
} else {
cell.itemStepper = (UIStepper *) [cell viewWithTag:2];
cell.itemAddedLbl =(UILabel*)[cell viewWithTag:1];
}
if (tableView == self.searchDisplayProduct.searchResultsTableView) {
cell.itemNameLbl.text= [[searchProductListArry objectAtIndex:indexPath.row] objectForKey:#"name"];
} else {
cell.itemNameLbl.text=[[productListArry objectAtIndex:indexPath.row] objectForKey:#"name"];
}
cell.itemCostLbl.text=[NSString stringWithFormat:#"%# %.2f", currencyCodeStr , [[[productListArry objectAtIndex:indexPath.row] objectForKey:#"offer"] floatValue]];
cell.itemAddedLbl.text = [[NSString alloc] initWithFormat:#"%d",itemCount];
cell.itemImg.image = [UIImage imageNamed:#"profp.jpg"];
return cell;
}
As you haven't post much of the information this is my guess.when you scroll table view it internally calls the reloadData method . You need to use reuse Identifier to preserve the state of the cell. You can initialize the cell in cellForRowAtIndexPath like :
static NSString *cellIdentifier = #"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
// or cell initializing logic here for the custom cell
}
in case of custom cell add reuse identifier in the xib and use it in your cellForRowAtIndexPath method

My custom cell does not display

I have created a custom cell that contain a Label but when I added that in my Table View than it does not display, my view controller is not TableViewController I have seted Table View using IB and seted its delegate and datasource correctly.
I am doing this by:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
ExampleAppDataObject* theDataObject = [self theAppDataObject];
return theDataObject.myAudio.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
ExampleAppDataObject* theDataObject = [self theAppDataObject];
NSString *destinationPath = [theDataObject.myAudio objectAtIndex:indexPath.row];
NSArray *parts = [destinationPath componentsSeparatedByString:#"/"];
NSString *filename = [parts lastObject];
AudioInfoCell *cell = (AudioInfoCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[AudioInfoCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
}
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
cell.audioName.text = filename;
return cell;
}
First check how many row set in tableView:numberOfRowsInSection method
After set the custom cell like bellow..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
AudioInfoCell *cell = (AudioInfoCell *) [tableView dequeueReusableCellWithIdentifier:nil];
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"AudioInfoCell" owner:self options:nil];
for (id currentObject in topLevelObjects){
if ([currentObject isKindOfClass:[UITableViewCell class]]){
cell = (AudioInfoCell *) currentObject;
break;
}
}
}
ExampleAppDataObject* theDataObject = [self theAppDataObject];
NSString *destinationPath = [theDataObject.myAudio objectAtIndex:indexPath.row];
NSArray *parts = [destinationPath componentsSeparatedByString:#"/"];
NSString *filename = [parts lastObject];
cell.audioName.text = filename;
return cell;
}
Two things to check:
Make sure the reuse identifier matches what is in Interface Builder
Make sure your numberOfRowsInSection and numberOfSectionsInTableView
return the right numbers
Also - I don't use:
if (cell == nil) {
cell = [[AudioInfoCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
}
for instantiating the cell. That should be taken care of in the AudioCell TableViewCell subclass you have implemented. An example of how I implement this kind of custom cell is:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"FlightPickerCell";
FlightPickerCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.tripIDLabel.text = #"Some TripID";
cell.hospitalLabel.text = #"Some Hospital";
cell.cityLabel.text = #"Some City";
return cell;
}

NSUser Defaults save button status and display again

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;
}
}

don't want to use dequeueReusableCellWithIdentifier for UITableViewCell

In my UITableViewCells I need to download different image for each cell, what should I do for such kind of problem...
You should use that method still, and then configure each cell independently. Just make sure your cell setup isn't on your construction block
UITableViewCell *cell = [tableView dequeue..];
if (!cell) {
cell = ...;
}
cell.image = ...;
item will be your dictionary of images
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MyIdentifier"]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:#"mainTitleKey"];
cell.detailTextLabel.text = [item objectForKey:#"secondaryTitleKey"];
NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:#"imageKey"] ofType:#"png"];
UIImage *theImage = [UIImage imageWithContentsOfFile:path];
cell.imageView.image = theImage;
return cell;
}

iPhone/iPad : table view scroll crash in ipad

Hi all I want to show more than 120 images in tableview its runs fine in simulator but crash in device (ipad).
logs show memory warning but I am releasing perfectly I don't know why I get this message and crash. Images comes from server I am using following code.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
FullTableViewCell *cell = (FullTableViewCell *)
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle]
loadNibNamed:#"FullTableViewCell" owner:nil options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (FullTableViewCell *)currentObject;
break;
}
}
}
NSDictionary *dic = [socketConnection().imageInfoArray objectAtIndex:indexPath.row];
int imageId = [[dic objectForKey:#"id"] intValue];
UIImage *image = [socketConnection().serverImageArray objectAtIndex:indexPath.row];
UIImage *IMMage = [self scaleImage:image toResolution:740];
cell.cellIMage.image = IMMage;
cell.addButton.tag = imageId;
cell.zoomOutButton.tag = imageId;
[cell.zoomOutButton addTarget:self action:#selector(_ZoomOut:) forControlEvents:UIControlEventTouchUpInside];
[cell.addButton addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
cell.transform = CGAffineTransformMakeRotation(3.14159265+(3.14159265/2));
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
plz anybody help me where i am wrong..
Implement:
if (cell) {
[cell setImage:nil];
[cell setImage://image];
// Put ALL cell code here
}
and release:
image and IMMage and FullTableView and topLevelObjects and dic before
return cell;
AND FINALLY AND MOST IMPORTANTLY:
also analyze you're project to see for leaks