How to implement check boxes functionality on UITableView in ios - ios

In my ios app I have added on one button in UITableViewCell which is for check and un-check the TableViewCell products. For this I wrote below code but according to my code by default all are checked and when I scroll check boxes are un-checking
my code:
- (void)viewDidLoad {
[super viewDidLoad];
checkBoxesArray = [[NSMutableArray alloc]init];
for(int i = 0; i <15; i++){
[checkBoxesArray addObject:#""];
}
}
//TableList Delegate Methods:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return checkBoxesArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"HistoryCell";
UITableViewCell *cell = (UITableViewCell *)[MaintableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
model1 = mainArray[indexPath.row];
cell.textLabel.text = model1.Name;
cell.detailTextLabel.text = model1.MasterId;
bool variable = checkBoxesArray[indexPath.row];
newBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[newBtn setFrame:CGRectMake(250,5,30,30)];
[newBtn addTarget:self action:#selector(urSelector:) forControlEvents:UIControlEventTouchUpInside];
UIImage *btnImage;
if(variable == YES){
NSLog(#"1");
btnImage = [UIImage imageNamed:#"check.png"];
}else{
NSLog(#"2");
btnImage = [UIImage imageNamed:#"uncheck.png"];
}
[newBtn setImage:btnImage forState:UIControlStateNormal];
[cell addSubview:newBtn];
return cell;
}
-(void)urSelector :(UIButton*)sender{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:MaintableView];
NSIndexPath *indexPath1 = [MaintableView indexPathForRowAtPoint:buttonPosition];
NSInteger variable = indexPath1.row;
bool variablePosition = checkBoxesArray[variable];
if (variablePosition == YES){
variablePosition= NO;
[checkBoxesArray replaceObjectAtIndex:variable withObject:[NSString stringWithFormat:#"%d",variablePosition]];
}
else{
variablePosition = YES;
[checkBoxesArray replaceObjectAtIndex:variable withObject:[NSString stringWithFormat:#"%d",variablePosition]];
}
[MaintableView reloadData];
}
#end

1) Add one key to your model array. Like isSelected and set it's value to NO.
2) Now when you select any cell at that time set the value of that key to YES.
3) In cellForRow, access that key which we have added and check it's value. If it's YES then set Check Image else Uncheck image.
4) Don't maintain two array so remove your checkboxarray. It will create confusion for you.

First Please replace your line of code in cellForRowAtIndexPath
bool variable = checkBoxesArray[indexPath.row];
with
bool variable = [checkBoxesArray[indexPath.row] length] > 0;
Because in checkBoxesArray , there are NSString type objects. and you are storing them into a bool variable . It always returns a true value to your 'variable'. So first of all you need to have a proper condition for 'check' and 'uncheck' thing. I am assuming that you want all boxes unchecked for the first time. So I put blank string for uncheck button and some value string for check button.
Again you need to replace your code in urSelctor method
bool variablePosition = checkBoxesArray[variable];
if (variablePosition == YES){
variablePosition= NO;
[checkBoxesArray replaceObjectAtIndex:variable withObject:[NSString stringWithFormat:#"%d",variablePosition]];
}
with
bool variablePosition = [checkBoxesArray[variable] length] > 0;
if (variablePosition == YES){
variablePosition= NO;
[checkBoxesArray replaceObjectAtIndex:variable withObject:#""];
}
hope these things will help you.
Happy coding... :) :) :)

Related

Objective-C pass tableView indexPath to another method

I have this cellForRowAtIndexPath method here:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
if (cell.accessoryView == nil) {
cell.accessoryView = [[Checkbox alloc] initWithFrame:CGRectMake(0, 0, 25, 43)];
cell.accessoryView.opaque = NO;
cell.backgroundColor = [UIColor clearColor];
[(Checkbox*)cell.accessoryView addTarget:self action:#selector(checkBoxTapped:forEvent:) forControlEvents:UIControlEventValueChanged];
}
NSString *sectionTitle = [contactSectionTitles objectAtIndex:indexPath.section];
NSArray *sectionContacts = [contactDirectoryFinal objectForKey:sectionTitle];
NSString *contacts = [[sectionContacts objectAtIndex:indexPath.row] valueForKey:#"item"];
cell.textLabel.text = contacts;
[(Checkbox*)cell.accessoryView setChecked: [[[sectionContacts objectAtIndex:indexPath.row] valueForKey:#"checkedItem"] boolValue] ];
return cell;
}
inside this method, I have this line:
[(Checkbox*)cell.accessoryView addTarget:self action:#selector(checkBoxTapped:forEvent:) forControlEvents:UIControlEventValueChanged];
which calls this method
- (IBAction)checkBoxTapped:(id)sender forEvent:(UIEvent*)event
{
}
What I am trying to do is adjust the way this method is called so I am also passing int the indexPath.row number
I got started with this:
[(Checkbox*)cell.accessoryView addTarget:self action:#selector(checkBoxTapped:forEvent:rowNumber:) forControlEvents:UIControlEventValueChanged];
and this
- (IBAction)checkBoxTapped:(id)sender forEvent:(UIEvent*)event rowNumber:(int)row
{
}
but I am new to selectors, my question is where do I pass in the rowNumber?
As you've found out you can't pass just any values with your selector, only the sender and the event. This is why you need another way pass the row number.
One method is to use the tag property on your control and retrieve it with [sender tag], however this approach will fail if the table indexes are changed without cellForRowAtIndexPath being called. It also won't work for sectioned table views.
A more robust approach is to use the location of your view to calculate the correct row. UITableView has a convenient method to do this:
- (IBAction)checkBoxTapped:(id)sender forEvent:(UIEvent*)event {
CGPoint checkBoxPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:checkBoxPosition];
}
As an alternative to passing it in ....
func checkBoxTapped(sender: CheckBox, withEvent event: UIEvent) {
if let tap = event.allTouches()?.first {
let location = tap.locationInView(tableView)
let indexPath = tableView.indexPathForRowAtPoint(location)
..... do something
}
}
*Update
As #Maddy 's comment
Do not use tag to represent the indexPath. It fails if the table view allows any rows to be moved, inserted, or deleted
this is not a good answer.*
As CheckBox is a UIView you can set its tag in cellForRowAtIndexPath: and then check for it in checkBoxTapped:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
if (cell.accessoryView == nil) {
cell.accessoryView = [[Checkbox alloc] initWithFrame:CGRectMake(0, 0, 25, 43)];
cell.accessoryView.opaque = NO;
cell.backgroundColor = [UIColor clearColor];
[(Checkbox*)cell.accessoryView addTarget:self action:#selector(checkBoxTapped:forEvent:) forControlEvents:UIControlEventValueChanged];
}
NSString *sectionTitle = [contactSectionTitles objectAtIndex:indexPath.section];
NSArray *sectionContacts = [contactDirectoryFinal objectForKey:sectionTitle];
NSString *contacts = [[sectionContacts objectAtIndex:indexPath.row] valueForKey:#"item"];
cell.textLabel.text = contacts;
[(Checkbox*)cell.accessoryView setChecked: [[[sectionContacts objectAtIndex:indexPath.row] valueForKey:#"checkedItem"] boolValue] ];
// set the index to the tag.
cell.accessoryView.tag = indexPath.row
return cell;
}
- (IBAction)checkBoxTapped:(id)sender forEvent:(UIEvent*)event
{
// get the index from the tag value
NSInteger row = ((UIView *)sender).tag
}
You could use:
- (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell
once you have the UITableViewCell object which can be accessed as sender.superview

Duplicated cell when scrolling. What should I do in order to prevent it?

I'm a newbie with iOS programming language. I try to use table with button in each row.
when i click button in the first cell, it work pretty well.
but when i scroll down, the cell that i don't click also appear click.
I want to show the clicked button in only cell(s) that I clicked?
Code:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{
ClassifyCustomCell * cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if ([[[arrayResult objectAtIndex:indexPath.row] objectForKey:#"COLABO_FLD_SRNO"] isEqualToString:#"I"]) {
cell.editButton.hidden = YES;
cell.folder_name.text = [[arrayResult objectAtIndex:indexPath.row] objectForKey:#"COLABO_FLD_NM"];
}else{
cell.editButton.hidden = NO;
cell.folder_name.text = [[arrayResult objectAtIndex:indexPath.row] objectForKey:#"COLABO_FLD_NM"];
cell.editButton.tag = indexPath.row;
[cell.editButton addTarget:self action:#selector(editButtonAction:) forControlEvents:UIControlEventTouchUpInside];
cell.checkButton.tag = indexPath.row;
[cell.checkButton addTarget:self action:#selector(checkButtonActoin:) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
-(void)checkButtonActoin:(UIButton *)sender{
if (sender.selected == YES) {
sender.selected = NO;
}else if(sender.selected == NO){
sender.selected = YES;
}else {
sender.selected = NO;
}
}
UITableView reuse the state of cell's subviews for new cells. To prevent reusing just configure your subviews explisitly in tableView:cellForRowAtIndexPath:. In your case you need to set selected property of your button to YES, if it was selected, and to NO, if it was not selected.
Add NSMutableArray property to your view controller:
#property (strong, nonatomic) NSMutableArray *arrayForSelectedIndexPaths;
Change your tap method:
-(void)checkButtonAction:(UIButton *)sender{
UITableViewCell *cell = (UITableViewCell *) sender.superview.superview...; //find appropriate number of superviews to get your cell
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
if (sender.selected) {
sender.selected = NO;
[self.arrayForSelectedIndexPaths removeObject:indexPath];
}else {
sender.selected = YES;
[self.arrayForSelectedIndexPaths addObject:indexPath];
}
}
Then in tableView:cellForRowAtIndexPath: add this line:
cell.checkButton.selected = [self.arrayForSelectedIndexPaths containsObject:indexPath];

Set button tag for different sections of UITableView

I list of contacts from Web Service and display it in contacts 'sectioned' tableView as seen in the screenshot.
Issue is I get same tag values for checkboxes of first row for section A as well as section S. I have sorted one array and displayed in the indexed table view. How to get different tag values depending on indexPath.row irrespective of number of sections displayed. Here's what I tried
In cellForRowAtIndexPath:
UIButton *checkBox;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(7, 8, 30, 30)];
}
else
{
checkBox = [[UIButton alloc]initWithFrame:CGRectMake(15, 13, 30, 30)];
}
//int cnt = 0;
// for (int i = indexPath.section - 1; i > 0 ; i--)
// {
// cnt += [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:i]] count]; //arrayOfCharachters has char 'A' to 'Z'
// }
//checkBox.tag = cnt + indexPath.row;
[checkBox setImage:[UIImage imageNamed:#"checkBox.png"] forState:UIControlStateNormal];
[checkBox addTarget:self action:#selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
[checkBox setTag:indexPath.row];
[cell.contentView addSubview:checkBox];
return cell;
}
-(void)checkBoxClicked:(id)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableViewContact];
NSIndexPath *indexPath = [self.tableViewContact indexPathForRowAtPoint:buttonPosition];
UIButton *tappedButton = (UIButton*)sender;
NSLog(#"Tag number = %d", [sender tag]);
if([tappedButton.currentImage isEqual:[UIImage imageNamed:#"checkBox.png"]])
{
[sender setImage:[UIImage imageNamed: #"checkBoxMarked.png"] forState:UIControlStateNormal];
if(indexPath != Nil)
{
NSString *finalIntId = [mutableArrayOfIds objectAtIndex:indexPath.row]; // store check box ids in mutableArrayOfIds
NSLog(#"Tagged checked button id = %#", finalIntId);
[arrayOfIds addObject:finalIntId];
}
//NSString *finalIntId = [mutableArrayOfIds objectAtIndex:tappedButton.tag];
//NSString *finalIntId = [mutableArrayOfIds objectAtIndex:indexPath.row];
}
else
{
[sender setImage:[UIImage imageNamed:#"checkBox.png"]forState:UIControlStateNormal];
NSLog(#"UnChecked");
//[arrayOfIds removeObjectAtIndex:tappedButton.tag];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if ([arrayOfCharacters count] == 0)
{
return #"";
}
return [NSString stringWithFormat:#"%#", [arrayOfCharacters objectAtIndex:section]];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
NSArray *toBeReturned = [NSArray arrayWithArray:
[#"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|#"
componentsSeparatedByString:#"|"]];
return toBeReturned;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
NSInteger count = 0;
for (NSString *character in arrayOfCharacters) {
if ([character isEqualToString:title]) {
return count;
}
count ++;
}
return 0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [arrayOfCharacters count];
//return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//return [mutableArray count];
return [[objectsForCharacters objectForKey:[arrayOfCharacters objectAtIndex:section]] count];
}
you are setting the same tag value for all sections which have same row.
The indexPath has two properties, {section,row}.
Lets say section A has two rows,
for row1 -> indexPath.section=0, indexPath.row=0;
for row2-> indexPath.section=0, indexPath.row=1;
Lets say section S has two rows,
for row1 -> indexPath.section=1, indexPath.row=0;
for row2-> indexPath.section=1, indexPath.row=1;
So, for row1 of section A and row1 of section S, you are setting the same tag value which is 0.There is your problem.
Try setting tag value like below.
button.tag = indexPath.section*1000 +indexPath.row;
when retrieving the section and row,
NSInteger section = (button.tag)/1000;
NSInteger row = (button.tag)%1000;
Try 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];
}
UIButton *checkBox =[[UIButton alloc] initWithFrame:CGRectMake(280, 10, 50, 44)];
checkBox.backgroundColor =[UIColor orangeColor];
[checkBox addTarget:self action:#selector(checkBoxClicked:event:)forControlEvents:UIControlEventTouchUpInside];
[checkBox setTag:indexPath.row];
[cell.contentView addSubview:checkBox];
return cell;
}
- (void)checkBoxClicked:(id)sender event:(id)event
{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tv]; //here tv is TableView Object
NSIndexPath *indexPath = [self.tv indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"value of indePath.section %d ,indexPath.row %d",indexPath.section,indexPath.row);
}
This is happening because you are assigning tag to buttons INDEPENDENT of sections.
Both of First Row of Sections A & S have row = 0. so Tag Assigned to their respective button is 0. You should assign them Keeping reference to your sections.
i would suggest to assign accessibility hint with comma separated form containing Section,Row.
And in your method
-(void)checkBoxClicked:(id)sender
{
//pick string from comma separated form. 1st is your section, 2nd is row.
}
second option is Do what ever your doing and implement your Button method like this.
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
if (indexPath != nil)
{
... indexpath.section is your section , index path.row is your row.
}
There is Third option as well.
in cellforRowAtIndexpath assign your Button a title
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
[btn setTitle:<#Your Row#> forState:UIControlStateDisabled];
[btn setTag<#Your Section#>];
so upon Receiving in your Button Method you can have both Section (Tag) and Row (Title for Disabled state).
-(void)checkBoxClicked:(id)sender { [button titleForState:UIControlStateDisabled]; // your Row
button.tag //your Section }
Try this!
Each section you may know the count of section right, then add count of individual row.
[[fieldTitlesList objectAtIndex:indexPath.section - 1] count] + indexPath.row
Where fieldTitlesList is the array of your sections.
I added the following code which solved my issue
NSInteger rowNumber = 0;
for(NSInteger i = 0; i < indexPath.section ; i++)
{
rowNumber += [self tableView:self.tableViewContact numberOfRowsInSection:i];
}
rowNumber += indexPath.row;
[checkBox setTag:rowNumber]; //checkBox is UIButton in cellForRowAtIndexPath

Custom cells reload issue while scrolling UITableView

I have a UITableView where in i am using a custom UITableViewCell. All is well until the UITableView is scrolled. As soon as i scroll the UITableView the cells in Second section starts showing the content of cell in the first section.
I am using Storyboard for my project.
Here is the code in cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
LS_Custom_Cell *customCell = (LS_Custom_Cell *)[tableView dequeueReusableCellWithIdentifier:#"LS_Custom_Cell" forIndexPath:indexPath];
if (indexPath.section == 0 && indexPath.row == 0) {
customCell.selectionStyle = UITableViewCellSelectionStyleNone;
[customCell.btnAddContact addTarget:self
action:#selector(btnAddContactAction:)
forControlEvents:UIControlEventTouchDown];
customCell.btnSelectContact.hidden = YES;
customCell.btnAddContact.hidden = NO;
customCell.lblAddContactText.hidden = NO;
customCell.lblContactName.hidden = YES;
customCell.lblContactEmailId.hidden = YES;
}else if (indexPath.section == 1){
customCell.lblContactName.text = [NSString stringWithFormat:#"%#", [[contactsArray objectAtIndex:indexPath.row] valueForKey:#"name"]];
customCell.lblContactEmailId.text = [NSString stringWithFormat:#"%#", [[contactsArray objectAtIndex:indexPath.row] valueForKey:#"email"]];
}
return customCell;
}
I am also attaching images in order to clarify the issue further.
This screenshot is the first time when table loads records seems perfect
http://postimg.org/image/y2114vjdl/
As soon as i start scrolling cell from the first section appears in second section
http://postimg.org/image/c5ei4i66x/
This is first time i am posting a question here so please forgive me if there are any mistakes. Any help in this regard would be very much appreciated. Thanks in advance.
Try this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
LS_Custom_Cell *customCell = (LS_Custom_Cell *)[tableView dequeueReusableCellWithIdentifier:#"LS_Custom_Cell" forIndexPath:indexPath];
if (indexPath.section == 0 && indexPath.row == 0)
{
customCell.selectionStyle = UITableViewCellSelectionStyleNone;
[customCell.btnAddContact addTarget:self
action:#selector(btnAddContactAction:)
forControlEvents:UIControlEventTouchDown];
customCell.btnSelectContact.hidden = YES;
customCell.btnAddContact.hidden = NO;
customCell.lblAddContactText.hidden = NO;
customCell.lblContactName.hidden = YES;
customCell.lblContactEmailId.hidden = YES;
}
else if (indexPath.section == 1)
{
customCell.btnSelectContact.hidden = NO;
customCell.btnAddContact.hidden = YES;
customCell.lblAddContactText.hidden = YES;
customCell.lblContactName.hidden = NO;
customCell.lblContactEmailId.hidden = NO;
customCell.lblContactName.text = [NSString stringWithFormat:#"%#", [[contactsArray objectAtIndex:indexPath.row] valueForKey:#"name"]];
customCell.lblContactEmailId.text = [NSString stringWithFormat:#"%#", [[contactsArray objectAtIndex:indexPath.row] valueForKey:#"email"]];
}
return customCell;
}

How to check if two objects (UIButtons ) are the same

First off tags wont work. I say this because i create 4 buttons all with the same tag for a specific cell i.e indexPath.row = tag.
Inside My TableViewCellForRowAtIndexpath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"courseCell";
//Step 1: Check to se if we can reuse a cell from a row that has just rolled off the screen
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//step 2: If there are no cell to reuse, create a new one
if (cell == nil){
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
}
...
//-------------Creation of Custom Buttons-------------//
//-----img = "radioOn.png"-----//
//----img2 = "radioOff.png"----//
//----RadioButtonA----//
...
radioButtonA = [UIButton buttonWithType:UIButtonTypeCustom];
[radioButtonA addTarget:self action:#selector(radioButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
radioButtonA.tag=indexPath.row;
//----End RadioButtonA----//
//----RadioButtonB----//
radioButtonB = [UIButton buttonWithType:UIButtonTypeCustom];
[radioButtonB addTarget:self action:#selector(radioButtonClicked:)forControlEvents:UIControlEventTouchUpInside];
radioButtonB.tag =indexPath.row;
...
//----End RadioButtonB----//
//----RadioButtonC----//
radioButtonC = [UIButton buttonWithType:UIButtonTypeCustom];
[radioButtonC addTarget:self action:#selector(radioButtonClicked:)forControlEvents:UIControlEventTouchUpInside];
radioButtonC.tag = indexPath.row;
...
//----End RadioButtonC----//
//----RadioButtonNA----//
radioButtonNA = [UIButton buttonWithType:UIButtonTypeCustom];
radioButtonNA.tag = indexPath.row;
[radioButtonNA addTarget:self action:#selector(radioButtonClicked:)forControlEvents:UIControlEventTouchUpInside];
...
//----End RadioButtonC----//
//---------End of Radio Button Creations---------//
//---------UIStepper & StepperLabel Creation-----//
[cell.contentView addSubview:radioButtonA];
[cell.contentView addSubview:radioButtonB];
[cell.contentView addSubview:radioButtonC];
[cell.contentView addSubview:radioButtonNA];
//Step4: Return the cell
return cell;
}
#pragma mark - Buttons
- (void)radioButtonClicked:(UIButton *)sender
{
UIButton *myButton = sender;
// This Method and all the ones similar to this method is created to handle the UITouchUpInsideEvent that the user sends when pressing the radioButtons A-NA.
[radioButtons addObject:sender];
// Create an instance(object) of class NSIndexPath called indexPath and set its value the indexPath of the cell the user is currently in.
UITableViewCell *cell = (UITableViewCell *)[[sender superview] superview];
NSIndexPath *indexPath = [myTableView indexPathForCell:cell];
// Initialize two unique variables in order to check if the buttons being clicked are being referenced in the correct index.
int row = indexPath.row;
NSLog(#"Button is in row %d", row);
...
}
-(IBAction)button:(UIButton*)sender{
...
#try {
for (i=0; i<8; i++) {
if ([credits count ] ==0) {
break;
}
HERE is where i am trying to access the radiobuttons i created in my cell. What i would like to do is this
if([credits objectAtIndex:i]) == radioButtonA{
do stuff. The reason im not saying == [radioButtonA tag] is because i have three other buttons all with the same tag. If your read the code u see why the tags are set this way.
}
What I am asking for is 1 help, and 2 is there another way to check if two Buttons i.e objects are equal without having to rely on their tags.
Do not worry about the Try catch finally i was using it to catch the exception being thrown.
if ([[[[credits objectAtIndex:i]titleLabel]text] isEqualToString:#"A"]) {
NSLog(#"radioA is in array");
creditHours+=[[valueArray objectAtIndex:i]doubleValue];
gradeEarned+=(GradeA.doubleValue *[[valueArray objectAtIndex:i]doubleValue]);
NSLog(#"%f",gradeEarned);
continue;
}
if ([[[[credits objectAtIndex:i]titleLabel]text] isEqualToString:#"B"]) {
NSLog(#"radioB is in array");
creditHours+=[[valueArray objectAtIndex:i]doubleValue];
gradeEarned+=(GradeB.doubleValue *[[valueArray objectAtIndex:i]doubleValue]);
continue;
}
if ([[[[credits objectAtIndex:i]titleLabel]text] isEqualToString:#"C"]){
NSLog(#"radioC is in array");
creditHours+=[[valueArray objectAtIndex:i]doubleValue];
gradeEarned+=(GradeC.doubleValue *[[valueArray objectAtIndex:i]doubleValue]);
continue;
}
if([credits objectAtIndex:i]== radioButtonNA){
NSLog(#"boboboobbobob");
continue;
}
}
}
#catch (NSException *exception) {
NSLog(#"NSException Caught");
NSLog(#"Name: %#",exception.name);
NSLog(#"Reason: %#", exception.reason);
}
#finally {
NSLog(#"in finally block");
}
// if ([credits objectAtIndex: i] == defaulter) {
// UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Failed to select all grades" message:[NSString stringWithFormat:#"Your grade selections have been reset"] delegate:self cancelButtonTitle:#"great"otherButtonTitles:nil];
// [alert show];
// [alert release];
// [self refreshArray];
// }
NSLog(#"%f",gradeEarned);
if (gradeEarned == 0) {
textLabel.text= [NSString stringWithFormat:#"%f",gradeEarned];
}else {
NSLog( #"boob");
sum= (gradeEarned)/(creditHours);
NSLog(#"%f",sum);
textLabel.text= [NSString stringWithFormat:#"%f",sum];
//[self refreshArray];
}
}
For more information Here is the log...
NSLog(#"%#",[credits objectAtIndex:i]);
NSLog(#"%#",radioButtonA);
THE First output is the log of the [credits object atIndex:i]
UIButton: 0x6c91430; frame = (86 110; 32 30); opaque = NO; layer = CALayer: 0x6c914f0
2012-06-20 20:24:01.568 TableView[12557:f803] UIButton: 0x6ea8ad0; frame = (86 110; 32 30); opaque = NO; tag = 6; layer = CALayer: 0x6e746e0
As you can see The UIBUttons are DIFFERENT thus == operator does not work
When checking two object against one another you cannot use ==, you have to use [objectA isEqual:objectB], if those two objects are the same the answer will be YES and NO if they are not.
To read more go to: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html
and check what is written for isEqual:
I'm not sure, in the method,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
you should add the buttons only when the cell is nil.just like this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"courseCell";
//Step 1: Check to se if we can reuse a cell from a row that has just rolled off the screen
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//step 2: If there are no cell to reuse, create a new one
if (cell == nil)
{
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
//-------------Creation of Custom Buttons-------------//
//-----img = "radioOn.png"-----//
//----img2 = "radioOff.png"----//
//----RadioButtonA----//
...
radioButtonA = [UIButton buttonWithType:UIButtonTypeCustom];
[radioButtonA addTarget:self action:#selector(radioButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
radioButtonA.tag=indexPath.row;
//----End RadioButtonA----//
//----RadioButtonB----//
radioButtonB = [UIButton buttonWithType:UIButtonTypeCustom];
[radioButtonB addTarget:self action:#selector(radioButtonClicked:)forControlEvents:UIControlEventTouchUpInside];
radioButtonB.tag =indexPath.row;
...
//----End RadioButtonB----//
//----RadioButtonC----//
radioButtonC = [UIButton buttonWithType:UIButtonTypeCustom];
[radioButtonC addTarget:self action:#selector(radioButtonClicked:)forControlEvents:UIControlEventTouchUpInside];
radioButtonC.tag = indexPath.row;
...
//----End RadioButtonC----//
//----RadioButtonNA----//
radioButtonNA = [UIButton buttonWithType:UIButtonTypeCustom];
radioButtonNA.tag = indexPath.row;
[radioButtonNA addTarget:self action:#selector(radioButtonClicked:)forControlEvents:UIControlEventTouchUpInside];
...
//----End RadioButtonC----//
//---------End of Radio Button Creations---------//
//---------UIStepper & StepperLabel Creation-----//
[cell.contentView addSubview:radioButtonA];
[cell.contentView addSubview:radioButtonB];
[cell.contentView addSubview:radioButtonC];
[cell.contentView addSubview:radioButtonNA];
}
...
//Step4: Return the cell
return cell;
}
I had already known this, however, the purpose of this post was to see if their are any other ways. I also used the isMemberOfClass:[UIButton class] to further narrow down. Best way and most effective way of doing this is using the object's tags to compare against.

Resources