Multiple Check Box in UITableview iPhone - iphone

I am new in iOS
I am creating dynamically buttons in my tableview
i had set a image on button for check and uncheck
What i have to do is when i tap(or check) on button the data on indexpath row will add in my array.
And if i deselect it , data removes from my array. Please Help me
-(void)btnForCheckBoxClicked:(id)sender
{
UIButton *tappedButton = (UIButton*)sender;
indexForCheckBox= [sender tag];
if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"checkbox_unchecked.png"]])
{
[sender setImage:[UIImage imageNamed: #"checkbox_checked.png"] forState:UIControlStateNormal];
strinForCheckBox= [ApplicationDelegate.ArrayForSearchResults objectAtIndex:indexForCheckBox];
[arrForCheckBox addObject:strinForCheckBox];
NSLog(#"Sender Tag When Add %d", indexForCheckBox);
NSLog(#"Array Count Check Box %d",[arrForCheckBox count]);
}
else
{
[sender setImage:[UIImage imageNamed:#"checkbox_unchecked.png"]forState:UIControlStateNormal];
[arrForCheckBox removeObjectAtIndex:indexForCheckBox];
NSLog(#"Sender Tag After Remove %d", indexForCheckBox);
NSLog(#"Array Count Uncheck Box %d",[arrForCheckBox count]);
}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
if ([selectedRowsArray containsObject:[contentArray objectAtIndex:indexPath.row]) {
cell.imageView.image = [UIImage imageNamed:#"checked.png"];
}
else {
cell.imageView.image = [UIImage imageNamed:#"unchecked.png"];
}
UITapGestureRecogniser *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleChecking:)
[cell.imageView addGestureRecognizer:tap];
[tap release];
cell.textLabel.text = [contentArray objectAtIndex];
return cell;
}
- (void) handleChecking:(UITapGestureRecognizer *)tapRecognizer {
CGPoint tapLocation = [tapRecognizer locationInView:self.tableView];
NSIndexPath *tappedIndexPath = [self.tableView indexPathForRowAtPoint:tapLocation];
if (selectedRowsArray containsObject:[contentArray objectAtIndex:tappedIndexPath.row]) {
[selectedRowsArray removeObject:[contentArray objectAtIndex:tappedIndexPath.row]];
}
else {
[selectedRowsArray addObject:[contentArray objectAtIndex:tappedIndexPath.row]];
}
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:tappedIndexPath] withRowAnimation: UITableViewRowAnimationFade];
}

I think this question has been answered some time ago! Check it out first and tell us if this is what you are looking for ?
How to add checkboxes to UITableViewCell??
image http://img208.yfrog.com/img208/6119/screenshotkmr.png

You can add this on your button click method.
First set Bool value which set yes on one click and No In second click and when you first click add that index value in array using array addobject property and other click removeobject property.
-(void)list
{
if(isCheck==YES)
{
//add array object here
isCheck=NO;
}
else if(isCheck==NO)
{
//remove array object here
isCheck=YES;
}
}

I have found another way. Code extracted from #The Saad And, i had just modified with key/value pairs as useful one like below code -
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
if ([[selectedRowsArray objectAtIndex:indexPath.row] containsObject:#"YES"])
cell.imageView.image = [UIImage imageNamed:#"checked.png"];
else
cell.imageView.image = [UIImage imageNamed:#"unchecked.png"];
UITapGestureRecogniser *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleChecking:)
[cell.imageView addGestureRecognizer:tap];
[tap release];
cell.textLabel.text = [contentArray objectAtIndex];
return cell;
}
- (void) handleChecking:(UITapGestureRecognizer *)tapRecognizer {
CGPoint tapLocation = [tapRecognizer locationInView:self.tableView];
NSIndexPath *tappedIndexPath = [self.tableView indexPathForRowAtPoint:tapLocation];
if ([[selectedRowsArray objectAtIndex:tappedIndexPath.row] containsObject:#"YES"])
[selectedRowsArray replaceObjectAtIndex:tappedIndexPath.row withObject:[NSSet setWithObject:#"NO"]];
else
[selectedRowsArray replaceObjectAtIndex:tappedIndexPath.row withObject:[NSSet setWithObject:#"YES"]];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:tappedIndexPath] withRowAnimation: UITableViewRowAnimationFade];
}
Add, the objects for selectedRowsArray as below with the count of your self.tableView's row count. So, you need to add the bool values as below
for ( int i = 0; i < tableViewRowCount; i++ ) { // tableViewRowCount would be your tableView's row count
....
....
....
[selectedRowsArray addObject:[NSSet setWithObject:#"NO"]];
....
....
}
Hope this helps! Cheers!
Update
With the use of updated code you don't need to keep key/value pair of NSMutableDictionary for overkilling that. NSSet provides you better way with this.

Related

Uitableview Accessorytype Checkmark Reset Code

I know how to handle with cellaccesory type check mark, here I want a button to Uncheck the entire tablecell which are checkmarked? Here my code, can any one please help me to code
- (void)viewDidAppear:(BOOL)animated
{
UIBarButtonItem *rest = [[UIBarButtonItem alloc]initWithTitle: #"RESET" style: UIBarButtonItemStyleBordered target: self action: #selector(uncheckCells)];
UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[toolbar setItems:[NSArray arrayWithObjects:rest,flexibleSpace,flexibleSpace,home,nil]];
[self.navigationController.view addSubview:toolbar];
[self.tableView reloadData];
}
Here the code for my functions
-(void)uncheckCells//unchecking function
{
[self.tableView reloadData];//HERE WHAT SHOULD I DO
}
-(void)hom
{
[self dismissModalViewControllerAnimated:YES];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [ar objectAtIndex:indexPath.row];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
if(cell.accessoryType==UITableViewCellAccessoryCheckmark)
{
cell.backgroundColor=UIColorFromRGB(0xd05818);
cell.detailTextLabel.text=#"packed";
cell.detailTextLabel.textColor=[UIColor cyanColor];
}
else
{
cell.backgroundColor=[UIColor whiteColor];
cell.detailTextLabel.text=#"";
}
return cell;
[self.tableView reloadData];
}
(void) deselect
{
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView reloadData];
[tableView deselectRowAtIndexPath:indexPath animated:NO];
printf("User selected row %d\n", [indexPath row] + 1);
if ([[tableView cellForRowAtIndexPath:indexPath] accessoryType] == UITableViewCellAccessoryCheckmark)
{
[[tableView cellForRowAtIndexPath:indexPath]setAccessoryType:UITableViewCellAccessoryNone];
}
else
[[tableView cellForRowAtIndexPath:indexPath]setAccessoryType:UITableViewCellAccessoryCheckmark];
[self performSelector:#selector(deselect) withObject:nil afterDelay:0.0f];
[tableView reloadData];
}
If you're doing checkmarks on didSelectRowAtIndexPath: method. A reloadData will work for you.
For eg.
Say you have a button with selector uncheckCells
-(void)uncheckCells
{
[self.tableView reloadData];
}
This should work you.
EDIT: add cell.accessoryType = UITableViewCellAccessoryNone; in your if (cell == nil) condition.
Or do this:
-(void)uncheckCells
{
for (int section = 0, sectionCount = self.tableView.numberOfSections; section < sectionCount; ++section) {
for (int row = 0, rowCount = [self.tableView numberOfRowsInSection:section]; row < rowCount; ++row) {
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row inSection:section]];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.accessoryView = nil;
}
}
}
I hope it will work.
From reading your code, it looks like you are setting the checkmark on the table view itself.
What you should really be doing is storing whether or not a cell has a check mark in your data source, and using this information in the tableView:cellForRowAtIndexPath: method to display a checkmark or not.
And your deselect method should be going through you datasource and unsetting whatever marker you have there that says whether or not your tableview has a check mark.
That way, when you scroll a tableview, or just call [tableView reloadData]; your datastore will be used to decide whether or not to display a checkmark or not.

How to tell which rows toggle switch was changed

I have a tableview with the accessoryview of a toggle switch. I specify the section and the row and am having a difficult time determining which row was toggled. I used the toggleSwitch.tag to grab the indexRow but as my indexRow is part of an indexPath.section I am not sure how to tell which row I toggled.
Here is the code:
- (UITableViewCell *)tableAlert:(SBTableAlert *)tableAlert cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell;
Category *cat = [allCategories objectAtIndex:indexPath.section];
Subject *sub = [cat.subjects objectAtIndex:indexPath.row];
cell = [[[SBTableAlertCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
UISwitch *toggleSwitch = [[UISwitch alloc] init];
cell.accessoryView = [[UIView alloc] initWithFrame:toggleSwitch.frame];
[cell.accessoryView addSubview:toggleSwitch];
cell.textLabel.text =sub.title;
cell.detailTextLabel.text = sub.category_title;
if (sub.active==1){
[toggleSwitch setOn:YES];
} else {
[toggleSwitch setOn:NO];
}
toggleSwitch.tag = indexPath.row;
[toggleSwitch addTarget:self action:#selector(viewButtonPushed:) forControlEvents:UIControlEventValueChanged];
[toggleSwitch release];
return cell;
}
- (void)viewButtonPushed:(id)sender {
UIButton *button = (UIButton *)sender;
UITableViewCell *cell = button.superview; // adjust according to your UITableViewCell-subclass' view hierarchy
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
Category *cat = [allCategories objectAtIndex:indexPath.section];
Subject *sub = [cat.subjects objectAtIndex:indexPath.row];
selectedSubject = sub;
UISwitch* switchControl = sender;
NSLog( #"The switch is %#", switchControl.on ? #"ON" : #"OFF" );
if(switchControl.on){
[sub setActive:1];
NSLog(#"%# is being set to ACTIVE", selectedSubject.title);
}else{
[sub setActive:0];
NSLog(#"%# is being set to INACTIVE", selectedSubject.title);
}
[sub setIsDirty:YES];
[cat.subjects replaceObjectAtIndex:indexPath.row withObject:sub];
[sub autorelease];
[cat autorelease];
}
Here is my didSelectRowAtIndexPath. Do I need to have any reference to the toggleSwitch here?
- (void)tableAlert:(SBTableAlert *)tableAlert didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
Category *cat = [allCategories objectAtIndex:indexPath.section];
Subject *sub = [cat.subjects objectAtIndex:indexPath.row];
selectedSubject = sub;
NSLog(#"selectedSubject = %#", selectedSubject.title);
if (tableAlert.type == SBTableAlertTypeMultipleSelct) {
UITableViewCell *cell = [tableAlert.tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone)
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
else
[cell setAccessoryType:UITableViewCellAccessoryNone];
[tableAlert.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
}
I have found that you need to go to the superview of the superview of the item in the cell (assuming that the button or control is right off the root of the cell) in order to get the pointer to the cell.
Try this instead:
UITableViewCell *cell = button.superview.superview;
and see if the results are any better. Check out my blog post on this for more information:
Two superviews are better than one

Objective-C: How to retain inputs and also tag names when UItextFields scrolled off?

My App is placing questions and according to the question, placing either UITextField or UISwitch.
When a user input texts it automatically detects which textField and placing the texts accordingly.
It works well but when the items are scrolled off, it removes the user inputs and tag names as well, and when displayes the area placing a new items on top of that.
So when a user input texts it stores it into the old textField.
I would like to know how to prevent it from this issue.
Is there any suggestion? Thanks in advance.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
NSLog(#"-------------cellForRowAtIndexPath---------------");
cell_id = [qid objectAtIndex:[indexPath row] ];
static NSString *CellIdentifier = #"Cell";
label = nil;
cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[self configureLabel];
[[cell contentView] addSubview:label];
}
dict = [qtext objectAtIndex:[indexPath row]];
celltext = [NSString stringWithFormat:#"%#\n\n\n",[[dict allKeys] objectAtIndex:0]];
dict = [qtype objectAtIndex:[indexPath row]];
type = [[dict allKeys] objectAtIndex:0];
//place the question
cell.textLabel.text = celltext;
NSLog(#"celltext=%#",celltext);
if([type isEqualToString:#"devider"]){
[self configureDevider];
}else{
[self configureCell];
}
if([cell_id intValue] == ([qid count])){
tabledone = #"Yes";
}
tableView.backgroundColor=[UIColor clearColor];
tableView.opaque=NO;
tableView.backgroundView=nil;
NSString *a = [arrAllheight objectAtIndex:[indexPath row]];
allheight +=thisheight;
thisheight =[a intValue];
if([type isEqualToString:#"YN"]){
DCRoundSwitch *ynSwitch = [[DCRoundSwitch alloc] initWithFrame:CGRectMake(220,thisheight-40,80,27)] ;
ynSwitch.onText=#"Yes";
ynSwitch.offText=#"No";
[answers addObject:ynSwitch];
[cell addSubview:ynSwitch];
[ynSwitch setTag:[cell_id intValue]];
[ynSwitch addTarget:self action:#selector(setAnswersForRoundSwitches:) forControlEvents:UIControlEventValueChanged];
i++;
}else if([type isEqualToString:#"freetext"]){
//When the done button was clicked, remove the keybords from the screen
[self makeTextField];
[rtxtfield addTarget:self action:#selector(setAnswersfortextFields:) forControlEvents:UIControlEventEditingDidEndOnExit];
// [rtxtfield value];
}else if([type isEqualToString:#"dropdown"]){
picc = [picker_array objectForKey:[[NSString alloc] initWithFormat:#"%d",cell_id]];
//Choose an array for this textField
// [self getPickerArray];
[self makeTextField];
//[rtxtfield addTarget:self action:#selector(setAnswersfortextFields:) forControlEvents:UIControlEventEditingDidEndOnExit];
//When the done button was clicked, remove the keybords from the screen
[rtxtfield addTarget:self action:#selector(textFieldReturn:) forControlEvents:UIControlEventEditingDidEndOnExit];
//Get the tag for picker
[rtxtfield addTarget:self action:#selector(getTag:) forControlEvents:UIControlEventTouchDown];
//Display picker
[rtxtfield addTarget:self action:#selector(acsheet:) forControlEvents:UIControlEventTouchDown];
//set Tag for the textField
[rtxtfield setTag:[cell_id intValue]];
NSLog(#"rtxtfield tag=%d",rtxtfield.tag);
}
if([type isEqualToString:#"devider"]){
[self caliculateHeightofCell];
}else{
[self caliculateHeightofCell];
}
return cell;
}
Save the state of your controls in your data model as soon as they change. So, maybe your model is an array of questions, and each question has an instance variable that can hold the answer. Your view controller is probably both the table data source and table delegate, and you should make it the target of any controls in the cells, too. That is, when you set up a new cell in your -tableView:cellForRowAtIndexPath:, make the view controller the target of the UITextField or UISwitch in the cell. When the user changes either of those controls, then, the change will trigger an action in the view controller, and the view controller can retrieve the new value of the control and store it in the corresponding question in the data model.
If you take this approach, you never have to worry about questions scrolling out of view. As soon as the question scrolls back into view, -tableView:cellForRowAtIndexPath: will be called for that row again, and you'll have all the information you need to reconstitute that cell.
Save the text to the dataSource. UITableViewCells must not contain any state information.
Implement something similar to this:
- (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];
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(2, 2, 200, 40)];
textField.tag = 999;
textField.delegate = self;
textField.placeholder = #"Enter text here";
[cell.contentView addSubview:textField];
}
UITextField *textField = (UITextField *)[cell.contentView viewWithTag:999];
textField.text = [self.dataSource objectAtIndex:indexPath.row];
/* configure cell */
return cell;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
UIView *contentView = [textField superview];
UITableViewCell *cell = (UITableViewCell *)[contentView superview];
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
[self.dataSource replaceObjectAtIndex:indexPath.row withObject:textField.text];
}
Do not add views outside of if (cell == nil)!
If you have different type of cells use a different CellIdentifier! Like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SwitchCellIdentifier = #"SwitchCell";
static NSString *TextFieldCellIdentifier = #"TextFieldCell";
UITableViewCell *cell = nil;
if (/* current cell is a text field cell */) {
cell = [tableView dequeueReusableCellWithIdentifier:TextFieldCellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TextFieldCellIdentifier];
// add textField
}
// configure cell...
}
else if (/* current cell is a switch cell */) {
cell = [tableView dequeueReusableCellWithIdentifier:SwitchCellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SwitchCellIdentifier];
// add switch
}
// configure cell...
}
return cell;
}
I took a day to fix the problem, but I've finally got it right:
Sorry it's a long code cause it's using textField, DCRoundSwitch, and pickerView.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"-----------------cellForRowAtIndexPath---------------");
Questions *q = [qtext objectAtIndex:indexPath.row];
NSLog(#"question=%#",q.question);
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
static NSString *SwitchCellIdentifier = #"SwitchCell";
static NSString *TextFieldCellIdentifier = #"TextFieldCell";
static NSString *DropDownFieldCellIdentifier = #"DropDownCell";
cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:TextFieldCellIdentifier];
if ([q.question_type isEqualToString:#"freetext"]) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TextFieldCellIdentifier];
if (cell == nil) {
[self makeTextField];
[cell.contentView addSubview:rtxtfield];
cell.textLabel.text = q.question;
}
[self makeTextField];
[self configureCell];
[self configureLabel];
cell.textLabel.text = q.question;
[cell.contentView addSubview:rtxtfield];
rtxtfield.text = [appDelegate.dataSource objectAtIndex:indexPath.row];
rtxtfield.tag=[indexPath row];
}else if([q.question_type isEqualToString:#"YN"]){
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SwitchCellIdentifier];
if (cell == nil) {
[self makeDCRoundSwitch];
[ynSwitch setTag:[indexPath row]];
cell.textLabel.text = q.question;
[self configureLabel];
[self configureCell];
}
[self makeDCRoundSwitch];
[ynSwitch setTag:[indexPath row]];
cell.textLabel.text = q.question;
[self configureLabel];
[self configureCell];
[ynSwitch addTarget:self action:#selector(ynSwitchDidEndEditing:) forControlEvents:UIControlEventValueChanged];
if([[appDelegate.dataSource objectAtIndex:indexPath.row] isEqualToString:#"Yes"]){
[ynSwitch setOn:YES animated:YES];
} else{
[ynSwitch setOn:NO animated:YES];
}
rtxtfield.tag=[indexPath row];
} else if([q.question_type isEqualToString:#"dropdown"]){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:DropDownFieldCellIdentifier];
if (cell == nil) {
[self makeTextField];
[cell.contentView addSubview:rtxtfield];
cell.textLabel.text = q.question;
}
[self makeTextField];
[self configureCell];
[self configureLabel];
cell.textLabel.text = q.question;
[cell.contentView addSubview:rtxtfield];
picc=q.question_array;
//When the done button was clicked, remove the keybords from the screen
[rtxtfield addTarget:self action:#selector(textFieldReturn:) forControlEvents:UIControlEventEditingDidEndOnExit];
//Get the tag for picker
[rtxtfield addTarget:self action:#selector(getTag:) forControlEvents:UIControlEventTouchDown];
//Display picker
[rtxtfield addTarget:self action:#selector(acsheet:) forControlEvents:UIControlEventTouchDown];
//set Tag for the textField
[rtxtfield setTag:[indexPath row]];
// AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
rtxtfield.text = [appDelegate.dataSource objectAtIndex:indexPath.row];
rtxtfield.tag=[indexPath row];
}
[self makeTextField];
rtxtfield.tag=[indexPath row];
tableView.backgroundColor=[UIColor clearColor];
tableView.opaque=NO;
tableView.backgroundView=nil;
return cell;
}
try this
label = nil;
//cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[self configureLabel];
[[cell contentView] addSubview:label];
//}
comment your code like that and tell me what happens

How to put the green Add icon unconditionally on the Insert row

I have a UITableView with a special row at the end to insert a new item. That works, but I want it to have the green plus icon without having to put the table view into editing mode. How can I do that?
I'd prefer not to create a button or bundle the image, if possible. Is there any way to do either or both of those things using only standard UITableView/UITableViewCell features?
you want to set the accessoryView to the cell:
#interface RootViewController : UITableViewController {
NSInteger nextValue;
NSMutableArray *timeIntervals;
}
#implementation RootViewController
- (NSNumber *)nextValue {
NSNumber *n = [NSNumber numberWithInteger:nextValue];
nextValue++;
return n;
}
- (void)viewDidLoad {
[super viewDidLoad];
nextValue = 1;
timeIntervals = [[NSMutableArray alloc] init];
[timeIntervals addObject:[self nextValue]];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [timeIntervals count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"TimeIntervalCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
UIButton *b = [UIButton buttonWithType:UIButtonTypeContactAdd];
[b addTarget:self action:#selector(addTapped:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = b;
}
NSNumber *number = [timeIntervals objectAtIndex:indexPath.row];
cell.accessoryView.tag = indexPath.row;
cell.textLabel.text = [number stringValue];
cell.detailTextLabel.text = #"detail about this number";
return cell;
}
- (void)addTapped:(UIButton *)sender {
id cell = sender;
while (cell != nil && [cell isKindOfClass:[UITableViewCell class]] == NO)
cell = [cell superview];
if (cell == nil) {
NSLog(#"[%# %#] sender was not in a cell",
NSStringFromClass([self class]), NSStringFromSelector(_cmd));
return;
}
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSInteger index = indexPath.row + 1; // insert after current cell
[timeIntervals insertObject:[self nextValue] atIndex:index];
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"[%# %#] not implemented", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
}
#end
(this is all the modified code to the Xcode 4.0.2 navigation app template)
You could implement your last cell as Custom Cell and add the green icon as per your choice.
See the tutorial to implement custom cell.
iPhone Programming Tutorial: Part 6: Creating custom UITableViewCell Using Interface Builder UITableView
Updated:
Let's say cell is the instance of UITabelViewCell.
First create a button using your green icon.
UIButton myGreenIconButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myGreenIconButton addTarget:self action:#selector(GreenIconButtonClicked:)forControlEvents:UIControlEventTouchUpInside];
[myGreenIconButton setBackgroundImage:[UIImage imageNamed:#"greenIcon.png"] forState:UIControlStateNormal];
myGreenIconButton.tag = i;
myGreenIconButton.backgroundColor = [UIColor clearColor];
myGreenIconButton.frame = CGRectMake(5, 78, 15, 15);
Now add it as subview in your last UITabelViewCell.
[cell addSubview:myGreenIconButton];
Implement GreenIconButtonClicked: method to receive the click evrnt on you add green icon button
-(void) GreenIconButtonClicked:(id) sender
{
}
Unfortunately, the only way I've found to do this is to set the cell's image, which means you have to handle the image files yourself instead of having UIKit load them for you. I recommend using the UIKit Artwork Extractor to get the image.

How to add checkboxes to UITableViewCell??

some time ago someone already asked this question and a few answers were given but i didn't really understand any of them. So i was wondering if anyone could please write an easy to understand tutorial on how to do the things shown on the image below:
http://img208.yfrog.com/img208/6119/screenshotkmr.png
I would be so greatful if anyone can share exactly how to this because it looks really cool and i would love to use something similar in my application :-)!
Make a unchecked and checked image..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
if ([selectedRowsArray containsObject:[contentArray objectAtIndex:indexPath.row]]) {
cell.imageView.image = [UIImage imageNamed:#"checked.png"];
}
else {
cell.imageView.image = [UIImage imageNamed:#"unchecked.png"];
}
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleChecking:)];
[cell.imageView addGestureRecognizer:tap];
cell.imageView.userInteractionEnabled = YES; //added based on #John 's comment
//[tap release];
cell.textLabel.text = [contentArray objectAtIndex:indexPath.row];
return cell;
}
- (void) handleChecking:(UITapGestureRecognizer *)tapRecognizer {
CGPoint tapLocation = [tapRecognizer locationInView:self.tableView];
NSIndexPath *tappedIndexPath = [self.tableView indexPathForRowAtPoint:tapLocation];
if ([selectedRowsArray containsObject:[contentArray objectAtIndex:tappedIndexPath.row]]) {
[selectedRowsArray removeObject:[contentArray objectAtIndex:tappedIndexPath.row]];
}
else {
[selectedRowsArray addObject:[contentArray objectAtIndex:tappedIndexPath.row]];
}
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:tappedIndexPath] withRowAnimation: UITableViewRowAnimationFade];
}
One of the way I can think of is you do custom UITableViewCell (this tutorial is good for starting. This is another, similar one). Inside the custom UITableViewCell you need to put a UIButton there with a circle image. When user select the button, you change the image to the green circle