Help me Checkbox's check mark is hidden - iphone

Please look at my following code snippet. I place check box in to my cell , i can able to check or uncheck the checkbox. but when i scroll the table view the checkbox's check mark is getting hidden.
i mean i set the check mark by setting the image.
Please anybody help me to solve this problem.
Thanks for your time.
// Customize the appearance of table view cells.
- (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:#"en"] autorelease];
cb = [[UIButton alloc] initWithFrame:CGRectMake(5,10, unselectedImage.size.width, unselectedImage.size.height)];
[cb setImage:unselectedImage forState:UIControlStateNormal];
[cb setImage:selectedImage forState:UIControlStateSelected];
[cb addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchDown];
[cell.contentView addSubview:cb];
}
if ( tableView == myTableView )
{
titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(60, 0, 150, 35)];
titleLabel.font = [UIFont boldSystemFontOfSize:13];
titleLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:titleLabel];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
return cell;
}

Taken from here
If I understand the TableView concept correctly, you need to save the checkmark setting somewhere else. If your cell gets scrolled out of view the TableViewController might release the cell. Then, when you're asked to re-create the cell in your delegate, you have to restore it in the same state as before.

In DidSelectRowAtindexPath:
if ([set containsObject:indexPath])
{
[set removeObject:indexPath];
}
else
{
[set addObject:indexPath];
}
and in CellForRpwAtIndexPath:
if ([set containsObject:indexPath])
{
cell.imgView.image=[UIImage imageNamed:#"chealBox1.png"];
}
else
{
cell.imgView.image=[UIImage imageNamed:#"chealBox2.png"];
}
here set is NSMutableSet and you have to make property and synthesize and alloc as well in viewDidLoad...will work definitely...

Related

Button in UITableView is appearing twice in iPad Master View Controller

Created a UITableView programmatically, data in my tableview in iPad Master View Controller is loaded dynamically, i am putting a button in the last cell, but the button is showing up again in the tableview underneath the cell... First time when the code is executed, the button appears only once, but next time it shows up twice... Here is the code...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if([_objects count] > 1)
{
if(indexPath.row == [_objects count])
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//set the position of the button
button.frame = CGRectMake(cell.frame.origin.x + 50, cell.frame.origin.y + 15, 225, 30);
[button setTitle:#"Hide me" forState:UIControlStateNormal];
[button addTarget:self action:#selector(customActionPressed) forControlEvents:UIControlEventTouchUpInside];
button.backgroundColor= [UIColor clearColor];
[cell.contentView addSubview:button];
}
else
{
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.textLabel.textColor = [UIColor colorWithRed:0/255.0 green:100.0/255.0 blue:220.0/255.0 alpha:1.0];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:13];
cell.textLabel.text = [_objects objectAtIndex:indexPath.row];
NSLog(#"%#", [_objects objectAtIndex:indexPath.row]);
}
}
return cell;
}
for ex:: here is a snapshot of the tableview (how can i put the image here???)
aaa
bbb
ccc
ddd
eee
UIButton
UIButton is appearing again here in the tableview
Here is the image link http://s10.postimg.org/fwarb2661/i_OS_Simulator_Screen_shot_28_Dec_2013_10_57_32_A.png
any help is appreciated, thanks in advance..
Please write bellow code :
if (cell)
{
cell =nil;
}
before creating your tableview cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//write here
if (cell)
{
cell =nil;
}
//*
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
For set background image in cell plese use bellow code :-
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(X, Y, 277, 58)];
imageView.backgroundColor = [UIColor clearColor];
imageView.opaque = NO;
imageView.image = [UIImage imageNamed:#"yourImage.png"];
cell.backgroundView = imageView;
Probably because your table view is using the same cell again.
Make sure you delete the button from the cell every time.
Would help to see your code so I can point to you exact location...
Try this:
(void)prepareForReuse {
[super prepareForReuse];
}
In the method set the button to nil or any other elements showing twice. The cell is being reused and you need to run prepareForReuse to empty the old cells.

Check Uncheck buttons in uitableview's cell

I have seen some posts before, but didn't get the answer yet, thats why i am trying to post again in more effective manner. How can i use check-uncheck functionality in UITableView like below image.
This is table i want when i click on button of any cell, that buttons image will change, not on all cells.
For Check-Uncheck functionality only buttonClicked: method is not enough. You will have also put the condition in cellForRowAtIndexPath: method for which button is selected or which in unselected because cellForRowAtIndexPath: method will call each time when you will scroll your UITableView and cells will be refresh.
And i saw your previous question you're adding two buttons with two action not a good way just change the image of button for check-uncheck.
So here is what i do for this -
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
{
IBOutlet UITableView *tblView;
NSMutableArray *arrayCheckUnchek; // Will handle which button is selected or which is unselected
NSMutableArray *cellDataArray; // this is your data array
}
#end
Now in ViewController.m class -
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayCheckUnchek = [[NSMutableArray alloc]init];
//Assign your cell data array
cellDataArray = [[NSMutableArray alloc]initWithObjects:#"cell-1",#"cell-2",#"cell-3",#"cell-4",#"cell-5", nil];
// setting all unchecks initially
for(int i=0; i<[cellDataArray count]; i++)
{
[arrayCheckUnchek addObject:#"Uncheck"];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [cellDataArray 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.text = [cellDataArray objectAtIndex:indexPath.row];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(270.0, 7.0, 30.0, 30.0)];
if([[arrayCheckUnchek objectAtIndex:indexPath.row] isEqualToString:#"Uncheck"])
[button setImage:[UIImage imageNamed:#"uncheck_icon"] forState:UIControlStateNormal];
else
[button setImage:[UIImage imageNamed:#"check_icon"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
return cell;
}
-(void)buttonClicked:(id)sender
{
//Getting the indexPath of cell of clicked button
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:tblView];
NSIndexPath *indexPath = [tblView indexPathForRowAtPoint:touchPoint];
// No need to use tag sender will keep the reference of clicked button
UIButton *button = (UIButton *)sender;
//Checking the condition button is checked or unchecked.
//accordingly replace the array object and change the button image
if([[arrayCheckUnchek objectAtIndex:indexPath.row] isEqualToString:#"Uncheck"])
{
[button setImage:[UIImage imageNamed:#"check_icon"] forState:UIControlStateNormal];
[arrayCheckUnchek replaceObjectAtIndex:indexPath.row withObject:#"Check"];
}
else
{
[button setImage:[UIImage imageNamed:#"uncheck_icon"] forState:UIControlStateNormal];
[arrayCheckUnchek replaceObjectAtIndex:indexPath.row withObject:#"Uncheck"];
}
}
And finally it will look like -
Tags are useful with customised uitableviewcell designed in IB. If you create cells programmatically, you don't need tags. You use them only to find correct uiview to set properties.
Yes this is simple to set Tags while declaring the classes inside UITableViewCell and identify them using tags. I have posted some sample code for your reference. Am not sure it will solve your problem. You asked how to set tags and identify the classes using tags. So it will give you some basic idea about your question.
-(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.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
label1 = [[UIView alloc] initWithFrame:CGRectMake(2, 20, 15, 15)];
label1.tag = 100;
label1.backgroundColor = [UIColor whiteColor];
label1.layer.cornerRadius = 5;
[cell.contentView addSubview: label1];
label2 = [[UILabel alloc] initWithFrame:CGRectMake(25, 2, 165, 23)];
label2.tag = 101;
label2.font = [UIFont boldSystemFontOfSize:15];
label2.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview: label2];
label3 = [[UILabel alloc] initWithFrame:CGRectMake(190, 2, 90, 23)];
label3.tag = 102;
label3.font = [UIFont systemFontOfSize:14];
label3.textColor = [UIColor colorWithRed:0.14117670588235 green:0.435294117647059 blue:0.847058823529412 alpha:1];
label3.backgroundColor = [UIColor clearColor];
label3.textAlignment = UITextAlignmentRight;
[cell.contentView addSubview: label3];
}
label1 = (UILabel *) [cell.contentView viewWithTag:100];
NSString *string1 = [array1 objectAtIndex:indexPath.row];
label2 = (UILabel *) [cell.contentView viewWithTag:101];
NSString * string2 = [array2 objectAtIndex:indexPath.row];
label3 = (UILabel *) [cell.contentView viewWithTag:102];
NSString * string3 = [array3 objectAtIndex:indexPath.row];
return cell;
}
Please let me know this is useful or not. Otherwise we'll go to some other way.
Happy Coding. Thanks.
i agree with #VakulSaini because u can do this to handle which cell touch or swipe or what ever and this is an ex:
-(void)handleSwipLeft:(UISwipeGestureRecognizer *)gestureRecognizer
{
CGPoint Location = [gestureRecognizer locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:Location];
cell = [tableView cellForRowAtIndexPath:indexPath];
}
Use cellForRowAtIndexPath method of UITableView and in This method Add any component like (UITextField,UILabel ..... etc ) In your UITableViewCell by using [cell.contentView addSubview:YourComponentName]; and give each component to its tag by indexPath.row.
such like ,,,
YourComponentName.tag = indexPath.row;

iPhone and Application Settings

I want to have a setting in an iphone app that uses a toggle switch to allow something to be turned on or off. I have seen tutorials, but they only show how to do this in the iPhone's settings place. I want this done inside the application. Any guides, help advice. I'm going for something similar to the picture below.
You can use the UISwitch as accessoryView. This will look (almost?) exactly like in your picture.
Something like this:
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease];
[mySwitch addTarget:self action:#selector(switchToggled:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = mySwitch;
}
// configure cell
UISwitch *mySwitch = (UISwitch *)cell.accessoryView;
mySwitch.on = YES; // or NO
cell.textLabel.text = #"Auto Connect";
return cell;
}
- (IBAction)switchToggled:(UISwitch *)sender {
UITableViewCell *cell = (UITableViewCell *)[sender superview];
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSLog(#"Switch %i,%i toggled", indexPath.section, indexPath.row);
}
You can use a UISwitch. Here's the very simple class reference guide.
http://developer.apple.com/library/ios/#documentation/uikit/reference/UISwitch_Class/Reference/Reference.html
Basically you can check its state by checking its "on" property.
if(mySwitch.on) {
//do something here
}
First, make sure you're UITableView style is set to "Grouped"
Then, in your cellForRowAtIndexPath method, do something along these lines:
if (indexPath.section == kSwitchSection) {
if (!randomControl) {
randomControl = [ [ UISwitch alloc ] initWithFrame: CGRectMake(200, 10, 0, 0) ];
[randomControl addTarget:self action:#selector(switchAction:) forControlEvents:UIControlEventValueChanged];
randomLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,8,180,30)];
[randomLabel setFont:[UIFont boldSystemFontOfSize:16]];
[randomLabel setText:#"My Label"];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[cell addSubview:randomControl];
[cell addSubview:randomLabel];
}
Remember to release the UISwitch object later and to include code for setting it to on or off depending on what state it should be in.

UITableView with multiple items in each cell

I have a tableview in which I am trying to place a button with an image and a label. I want to change the image of the button once clicked.
Here's the code:
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
checkedImg = [UIImage imageNamed:#"buttonUnChecked1.png"];
UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
//Set up the cell...
NSString *cellValue = [suggestions objectAtIndex:indexPath.row];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
check = [UIButton buttonWithType:UIButtonTypeCustom];
check.frame=CGRectMake(0,35,20,20);
[check setImage:checkedImg forState:UIControlStateNormal];
[check addTarget:self action:#selector(checkClicked:) forControlEvents: UIControlEventTouchUpInside];
[cell.contentView addSubview:check];
cellContent = [[UILabel alloc]initWithFrame:CGRectMake(40,32,500,25)];
cellContent.text = cellValue;
[cell.contentView addSubview:cellContent];
return cell;
}
-(void)checkClicked:(UIButton *)b
{
checkedImg = [UIImage imageNamed:#"buttonChecked1.png"];
[check setImage:checkedImg forState:UIControlStateNormal];
}
By doing this, the image of the buttons are getting changed but only the last one and not the one clicked. I know the reason behind it, but I don't know how to achieve what I want.
A structured way to get the result you're looking for:
Make a UIView subclass that for your table cells (containing a button and label). You instantiate these custom views and set them as your contentView for each table cell in cellForRowAtIndexPath.
Each of your custom views listens for its own button being pressed. When it was pressed, it toggles its state and tells the main viewcontroller (via a delegate method) that it was toggled. The main view controller calls reloadData on the cell in question to cause it to be reloaded with the correct appearance.
Note that this approach requires you to tell each of the custom views which index path it is rendering for in the table -- that way it can inform the main view controller's delegate method -- this info is needed for triggering a reload of the appropriate cell.
Btw, I presume you want to look at the state of the buttons in your table when the user is done with editing, and your current approach doesn't capture the state stuff very explicitly -- you'd have to iterate over your buttons, or add selected items to a mutable array, or something.
The easy answer to your problem is to change your checkClicked: method to this:
-(void)checkClicked:(UIButton *)b
{
[b setImage:[UIImage imageNamed:#"buttonChecked1.png"] forState:UIControlStateNormal];
}
But you should also adjust your tableView:cellForRowAtIndexPath: method to avoid creating the button repeatedly and to clean up some memory issues like this:
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIButton *checkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
checkBtn.frame = CGRectMake(0,35,20,20);
[checkBtn setImage:[UIImage imageNamed:#"buttonUnChecked1.png"]; forState:UIControlStateNormal];
[checkBtn addTarget:self action:#selector(checkClicked:) forControlEvents: UIControlEventTouchUpInside];
[cell.contentView addSubview:checkBtn];
UILabel *cellContentLbl = [[UILabel alloc]initWithFrame:CGRectMake(40,32,500,25)];
cellContentLbl.tag = 1;
[cell.contentView addSubview:cellContentLbl];
[cellContentLbl release];
}
//Set up the cell...
NSString *cellValue = [suggestions objectAtIndex:indexPath.row];
cellContent = (UILabel *)[cell viewWithTag:1];
cellContent.text = cellValue;
return cell;
}

iphone: how to add checkboxes to a uitableviewcell?

I just can't seem figure out how to do this hopefully someone here can help me. In my tableview i want to add checkboxes to each cell and if you touch the checkbox a checkmark appears and a specific action is supposed to happen. but if you just touch the cell a different action is supposed to happen. Does anyone have an idea how to do this?? I started doing the following. But i think my approach creates memory leaks and i don't know how to perform an action only for the button that was pressed instead for all of them.....
It would be great if someone could help me out....
- (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];
}
NSArray *tempArray = [[exerciseNames objectAtIndex:indexPath.section] objectForKey:#"rowValues"];
UIButton *checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
checkButton.tag = indexPath.row;
[checkButton setFrame:CGRectMake(10, 10, 23, 23)];
if (checkButtonPressed == YES) {
[checkButton setBackgroundImage:[[UIImage imageNamed:#"checked.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
}
else {
[checkButton setBackgroundImage:[[UIImage imageNamed:#"unchecked.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
}
[checkButton addTarget:self action:#selector(checkAction) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:checkButton];
cell.imageView.image = [UIImage imageNamed:#"unchecked.png"];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.text = [NSString stringWithFormat:#"%# (%#)", [[tempArray objectAtIndex:indexPath.row] objectForKey:#"full"], [[tempArray objectAtIndex:indexPath.row] objectForKey:#"short"]];
// Set up the cell...
return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:#"CellWithSwitch"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CellWithSwitch"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.font = [UIFont systemFontOfSize:14];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
cell.textLabel.text = #"Sound Effects";
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)path {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:path];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
} else {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
I would try subclassing UITableViewCell and make each cell the target of the buttons action. That way when the button is pressed, the event will be handled by the cell object, not the table controller. If you don't like that, you could try using the tag your assigning to the button to make a distinction. To do that, make your button selector be
checkAction:(UIButton *)_btn {}
and when you add the target,
[checkButton addTarget:self action:#selector(checkAction:) forControlEvents:UIControlEventTouchUpInside];
(notice the : at the end of the #selector())
I haven't tried the second way, but I think it would work.
In Cocoa Touch, a UISwitch is the UI paradigm equivalent for a checkbox on a desktop UI.
Your checkAction handler can check which control called it, and only change that one control.