Uncheck row automatically when table scrolled - ios

When I scroll UITableView my tableview cells automatically uncheck. But when I press done button it give me selected rows I can't understand why is this happening.
My Tableview code is as below :
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
idArray = [[NSMutableArray alloc]init];
NSLog(#"Cat Array : %#",catArray);
isSelectAllBtnClicked = NO;
serviceArray = [[NSArray alloc]initWithObjects:#"Anal", #"Cuffed", #"Foreplay", #"Masturbation", #"Scat", #"Blindfolded",#"Deep throat", #"French Kissing", #"Missionary", #"Shower for 2", #"Bottom", #"Dinner Date", #"Full Bondage", #"Mutual Masturbation", #"Spanking", #"Boy on Boy", #"Dirty Talk",#"Girl on Girl", #"On top", #"Strap on", #"Choking", #"Doggy", #"Girlfriend Experience", #"Oral", #"Striptease", #"CIM", #"Dominate", #"Golden Shower",#"Oral Mutual", #"Submissive", #"COB", #"Fantasy", #"Kissing", #"Overnight", #"Top", #"COF", #"Fetish", #"Light Bondage", #"Rim me",#"Touching", #"Couples", #"Fisting", #"Lingerie", #"Rim you", #"Toys for me", #"Cuddling", #"Foot fetish", #"Massage", #"Role Play", #"Toys for you", nil];
[myTableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reuseIdentifier = #"reuseIdentifier";
UITableViewCell *cell = [[UITableViewCell alloc]init];
if (cell != NULL)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
}
cell.selectionStyle = UITableViewCellEditingStyleNone;
cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"list_row_bg.png"]] autorelease];
UILabel *catListLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 310, 20)];
NSString *strValue = [[NSUserDefaults standardUserDefaults]valueForKey:#"service"];
if ([strValue isEqualToString:#"service"])
{
catListLbl.text = [serviceArray objectAtIndex:indexPath.row];
topHaderLabel.text = #"Choose Services";
}
else
{
catListLbl.text = [catArray objectAtIndex:indexPath.row];
topHaderLabel.text = #"Choose Category";
}
catListLbl.textColor = [UIColor colorWithRed:244/255.0 green:29/255.0 blue:94/255.0 alpha:1.0];
catListLbl.backgroundColor = [UIColor clearColor];
[cell addSubview:catListLbl];
if (isSelectAllBtnClicked) {
UIButton *unCheckBtn = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 20, 20)];
[unCheckBtn setBackgroundImage:[UIImage imageNamed:#"checkbox_check.png"] forState:UIControlStateNormal];
unCheckBtn.tag = indexPath.row + 200;
//NSLog(#"%i",unCheckBtn.tag);
[cell addSubview:unCheckBtn];
[myTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
[self tableView:myTableView didSelectRowAtIndexPath:indexPath];
}
else {
UIButton *unCheckBtn = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 20, 20)];
[unCheckBtn setBackgroundImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
unCheckBtn.tag = indexPath.row + 200;
//NSLog(#"%i",unCheckBtn.tag);
[cell addSubview:unCheckBtn];
}
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int buttonTag = indexPath.row + 200;
//NSLog(#"%i",buttonTag);
UIButton *tempBtn = (UIButton *)[self.view viewWithTag:buttonTag];
[tempBtn setBackgroundImage:[UIImage imageNamed:#"checkbox_check.png"]forState:UIControlStateNormal];
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
int buttonTag = indexPath.row + 200;
NSLog(#"%i",buttonTag);
UIButton *tempBtn = (UIButton *)[self.view viewWithTag:buttonTag];
[tempBtn setBackgroundImage:[UIImage imageNamed:#"checkbox.png"]forState:UIControlStateNormal];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int count;
NSString *strValue = [[NSUserDefaults standardUserDefaults]valueForKey:#"service"];
if ([strValue isEqualToString:#"service"])
{
count = [serviceArray count];
}
else
{
count = [catArray count];
}
return count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 40;
}
thanks in advance.

when ever you scroll the table
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
method executes and you have not mentioned any condition by which it can be judged that this row was previously selected or not. you have to insert a condition along with indexPath.row and check whether it is prviously selected or not

try like this ,when you scroll the tableview every time isSelectAllBtnClicked value is 0 that's why every time button changed.
when you scroll the table every time new cell created try to avoid that one
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *CellIdentifier = [NSString stringWithFormat:#"%d",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell.selectionStyle = UITableViewCellEditingStyleNone;
cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"list_row_bg.png"]] autorelease];
UILabel *catListLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 310, 20)];
NSString *strValue = [[NSUserDefaults standardUserDefaults]valueForKey:#"service"];
if ([strValue isEqualToString:#"service"])
{
catListLbl.text = [serviceArray objectAtIndex:indexPath.row];
topHaderLabel.text = #"Choose Services";
}
else
{
catListLbl.text = [catArray objectAtIndex:indexPath.row];
topHaderLabel.text = #"Choose Category";
}
catListLbl.textColor = [UIColor colorWithRed:244/255.0 green:29/255.0 blue:94/255.0 alpha:1.0];
catListLbl.backgroundColor = [UIColor clearColor];
[cell addSubview:catListLbl];
if (isSelectAllBtnClicked) {
UIButton *unCheckBtn = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 20, 20)];
[unCheckBtn setBackgroundImage:[UIImage imageNamed:#"checkbox_check.png"] forState:UIControlStateNormal];
unCheckBtn.tag = indexPath.row + 200;
//NSLog(#"%i",unCheckBtn.tag);
[cell addSubview:unCheckBtn];
[myTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
[self tableView:myTableView didSelectRowAtIndexPath:indexPath];
}
else {
UIButton *unCheckBtn = [[UIButton alloc]initWithFrame:CGRectMake(270, 10, 20, 20)];
[unCheckBtn setBackgroundImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
unCheckBtn.tag = indexPath.row + 200;
//NSLog(#"%i",unCheckBtn.tag);
[cell addSubview:unCheckBtn];
}
}
}

Related

Tableview scrolling Checked button image automatically hide

I am developing IOS App. Using tableview to expand and collpase. Add Button on TableviewCell for check or Uncheck. Example I am Selected First Row button. Than scrolling tableview and select last header to last row button selected. Than again scrolling and see first index selected button image hidden.
Code..
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (self.sectionNames.count > 0) {
_tableView.backgroundView = nil;
return self.sectionNames.count;
}
return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSMutableArray *arrayOfItems = [self.sectionItems objectAtIndex:section];
return arrayOfItems.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (self.sectionNames.count) {
return [self.sectionNames objectAtIndex:section];
}
return #"";
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section; {
return 44.0;
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
// recast your view as a UITableViewHeaderFooterView
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
// header.contentView.backgroundColor = [UIColor colorWithHexString:#"#484848"];
header.contentView.backgroundColor = [UIColor lightGrayColor];
header.textLabel.textColor = [UIColor whiteColor];
header.textLabel.font = [UIFont fontWithName:#"SourceSansPro SemiBold" size:15.0];
UIImageView *viewWithTag = [self.view viewWithTag:kHeaderSectionTag + section];
if (viewWithTag) {
[viewWithTag removeFromSuperview];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = nil;
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// for(UIView *subview in [cell subviews]) {
// [subview removeFromSuperview];
// }
UILabel *sectionLabel = [[UILabel alloc]initWithFrame:CGRectMake(35.0f, 12.0f, 120.0f, 20.f)];
sectionLabel.font = [UIFont systemFontOfSize:14.0f];
sectionLabel.textColor = [UIColor blackColor];
sectionLabel.lineBreakMode = NSLineBreakByWordWrapping;
sectionLabel.numberOfLines = 3;
[cell addSubview:sectionLabel];
NSArray *section = [self.sectionItems objectAtIndex:indexPath.section];
sectionLabel.text = [section objectAtIndex:indexPath.row];
UIButton *button = [[UIButton alloc]initWithFrame: CGRectMake(5.0f, 9.0f, 25.0f, 25.0f)];
button.layer.borderColor=[[UIColor colorWithRed:244.0f/255.0f
green:129.0f/255.0f
blue:32.0f/255.0f
alpha:1.0] CGColor];
[button.layer setBorderWidth: 1.0];
button.tag = indexPath.section;
NSString *data = [section objectAtIndex:indexPath.row]; //For Selected Fliters
for (int i=0; i<[filterArray count]; i++) {
NSDictionary *dict = [filterArray objectAtIndex:i];
NSString *fliterTickValue = [dict valueForKey:#"filterValue"];
if ([fliterTickValue isEqualToString:data]) {
UIImage *img = [UIImage imageNamed:#"tick.png"];
[button setImage: img forState:UIControlStateNormal];
}else{
UIImage *img = [UIImage imageNamed:#""];
[button setImage: img forState:UIControlStateNormal];
}
}
[button addTarget:self action:#selector(fliterFields:) forControlEvents:UIControlEventTouchDown];
[cell addSubview:button];
return cell;
}
Imho, your calls [cell addSubview:] is not correct. In case that cell is re-used, it will already have those subviews and resulting layout of your cell is not quite clear.
I suggest you to design your cell in xib and load it when needed. Then your cellForRowAtIndexPath becomes simpler and deals mostly with data populating. Subviews you don't need at the moment can be hidden and so on. If you need code and design example - let me know.

Expand and collapse the tableview row

I am developing an iOS application. I have one expandable and collapsed tableview. On click the cell of tableview, the tableview cell expands properly but when I click on a second cell I want first cell to collapse and the second to expand. This would leave only one cell expanded at a time.
I am using class HVTableview:-
Code:-
-(void)tableView:(UITableView *)tableView expandCell: (UITableViewCell*)cell withIndexPath:(NSIndexPath*) indexPath;
{
UILabel *detail = (UILabel *)[cell viewWithTag:3];
UIButton *button = (UIButton *)[cell viewWithTag:10];
button.alpha = 0;
button.hidden = NO;
[UIView animateWithDuration:.5 animations:^{
detail.text = #"This is Expand.";
button.alpha = 1;
[cell.contentView viewWithTag:7].transform = CGAffineTransformMakeRotation(3.14);
}];
}
-(void)tableView:(UITableView *)tableView collapseCell: (UITableViewCell*)cell withIndexPath:(NSIndexPath*) indexPath;
{
UILabel *detail = (UILabel *)[cell viewWithTag:3];
UIButton *button = (UIButton *)[cell viewWithTag:10];
button.alpha = 0;
[UIView animateWithDuration:.5 animations:^{
detail.text = #"This is Collapse.";
button.alpha = 0;
[cell.contentView viewWithTag:7].transform = CGAffineTransformMakeRotation(-3.14);
} completion:^(BOOL finished) {
button.hidden = YES;
}];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_cites count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath isExpanded: (BOOL)isExpanded;
{
if (isExpanded) {
return 150;
}else
{
return 100;
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath isExpanded:(BOOL)isExpanded;
{
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UILabel *title = (UILabel *)[cell viewWithTag:2];
UILabel *detail = (UILabel *)[cell viewWithTag:3];
UIImageView *image = (UIImageView *)[cell viewWithTag:1];
UIButton *button = (UIButton *)[cell viewWithTag:10];
[button addTarget:self action:#selector(goToTop) forControlEvents:UIControlEventTouchUpInside];
title.text = [_cites objectAtIndex:indexPath.row % 9];
NSString* bundlePath = [[NSBundle mainBundle] bundlePath];
NSString* imageFileName = [NSString stringWithFormat:#"%d.jpg", indexPath.row % 9 + 1];
image.image = [[UIImage alloc] initWithContentsOfFile:[NSString stringWithFormat:#"%#/%#", bundlePath, imageFileName]];
if (indexPath.row %2 ==1)
cell.backgroundColor = [UIColor colorWithRed:.9 green:.9 blue:.9 alpha:1];
else
cell.backgroundColor = [UIColor colorWithRed:.8 green:.8 blue:.8 alpha:1];
if (!isExpanded)
{
detail.text = #"This is collapse";
[cell.contentView viewWithTag:7].transform = CGAffineTransformMakeRotation(0);
button.hidden = YES;
}
else
{
detail.text = #"This is Expand";
[cell.contentView viewWithTag:7].transform = CGAffineTransformMakeRotation(3.14);
button.hidden = NO;
}
return cell;
}
- (void) collapseExpandButtonTap:(id) sender
{
UIButton* aButton = (UIButton*)sender; //It's actually a button
NSIndexPath* aPath = [self indexPathForCellWithButtonTag:aButton.tag]; //Let's assume that you have only one section and button tags directly correspond to rows of your cells.
//expandedCells is a mutable set declared in your interface section or private class extensiont
if ([expandedCells containsObject:aPath])
{
[expandedCells removeObject:aPath];
}
else
{
[expandedCells addObject:aPath];
}
[myTableView beginEditing];
[myTableView endEditing]; //Yeah, that old trick to animate cell expand/collapse
}
In UITableViewDelegate method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([expandedCells containsObject:indexPath])
{
return kExpandedCellHeight; //It's not necessary a constant, though
}
else
{
return kNormalCellHeigh; //Again not necessary a constant
}
}
Key thing here is to determine if your cell should be expanded/collapsed and return right height in delegate method. So accordingly design your requirements.

How to change button background color which is added on table view cell when we tapped on it?

I have added one custom button on tableview cell and everything is ok.
But here my main requirement is when I click that button for the "first time" which is added on table view cell, then the button background color needs to change(to red) and when I click the second time the button, the previous color needs to be displayed(back to white)
My code:
#import "ViewController2.h"
#interface ViewController2 ()
{
NSArray * Mainarray;
UITableView * MaintableView;
UIImageView * accessoryView;
UIButton *button;
BOOL tapped;
}
#end
#implementation ViewController2
- (void)viewDidLoad
{
[super viewDidLoad];
tapped = NO;
Mainarray = [[NSArray alloc]initWithObjects:#"Ram",#"Rama",#"Rakesh",#"Ranjith", nil];
self.view.backgroundColor = [UIColor darkGrayColor];
MaintableView = [[UITableView alloc]init];
MaintableView.translatesAutoresizingMaskIntoConstraints = NO;
MaintableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
MaintableView.dataSource=self;
MaintableView.delegate=self;
MaintableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
[MaintableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"Cell"];
[self.view addSubview:MaintableView];
NSDictionary * views = NSDictionaryOfVariableBindings(MaintableView);
NSArray * horizentalConstraint = [NSLayoutConstraint constraintsWithVisualFormat:#"H:|-0-[MaintableView]-0-|" options:0 metrics:nil views:views];
NSArray * verticalConstraint = [NSLayoutConstraint constraintsWithVisualFormat:#"V:|-0-[MaintableView]-0-|"options:0 metrics:nil views:views];
[self.view addConstraints:horizentalConstraint];
[self.view addConstraints:verticalConstraint];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return Mainarray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 50;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *Cell = [MaintableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (Cell == nil)
{
Cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.textLabel.text = [Mainarray objectAtIndex:indexPath.row];
button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag=indexPath.row;
[button addTarget:self
action:#selector(aMethod:) forControlEvents:UIControlEventTouchDown];
[button setTitle:#"" forState:UIControlStateNormal];
button.frame = CGRectMake(Cell.frame.size.width - 50, 10, 30, 30);
button.layer.cornerRadius = 60/2.0f;
button.layer.borderColor=[UIColor blackColor].CGColor;
button.backgroundColor = [UIColor whiteColor];
button.layer.borderWidth=2.0f;
//setting tag to button
button.tag=indexPath.row;
[Cell.contentView addSubview:button];
return Cell;
}
-(void)aMethod :(id)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:MaintableView];
NSIndexPath *indexPath1 = [MaintableView indexPathForRowAtPoint:buttonPosition];
NSInteger variable = indexPath1.row;
NSLog(#"ok it is %ld",(long)variable);
if(button.tag == variable){
button.backgroundColor= tapped ? [UIColor whiteColor]:[UIColor redColor];
tapped = YES;
}
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell respondsToSelector:#selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:#selector(setPreservesSuperviewLayoutMargins:)]) {
[cell setPreservesSuperviewLayoutMargins:NO];
}
if ([cell respondsToSelector:#selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
#end
You can create an array in which u can store selected buttons.
Example:
var selectedButtons: [Bool] = [Bool](count: N, repeatedValue: false)
In your cellForRowAtIndexPath:
if selectedButtons[indexPath.row] {
yourButton.backgroundColor = UIColor.redColor()
} else {
yourButton.backgroundColor = UIColor.whiteColor()
}
Then in your tableView didSelectRowAtIndexPath you can say:
selectedButtons[indexPath.row] = true
tableView.reloadData()
Sorry, my code is in Swift but it isn't hard to convert it to Obj-C.
Give your button a tag value in the cellForRowIndexpath method:
button.tag=indexPath.row;
and in your view did load, make the BOOL as a property in your .m file and make it accessible for the whole class
BOOL tapped =NO;
and then in your button action method:
-(IBAction)buttonMethod:(id)sender{
if(sender.tag==0){
button.backgroundColor= tapped ? [UIColor whiteColor]:[UIColor redColor];
tapped = !tapped;
}
}
Please try below code. Hope this is work for you.
-(void)aMethod:(id)sender
{
UIButton *btn = (UIButton *)sender;
if ([btn.backgroundColor isEqual:[UIColor redColor]]) {
btn.backgroundColor = [UIColor whiteColor];
}
else{
btn.backgroundColor = [UIColor redColor];
}
}
Thanks.. :)
I tried to get the solution for your question and finally i got.
First you have to change Button Type RECT to CUSTOM in Attributes Inspector.Because in button type RECT the default background color of button is BLUE.So when you click for changing the color of the button, it comes actual color(it changes to your required color) with BLUE color.So you need to set the button type as CUSTOM.
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrayButtonData.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
customCell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:#"cell"];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:self options:nil];
if (customCell==nil)
{
customCell = [nib objectAtIndex:0];
}
customCell.labelArrayListsNames.text = [NSString stringWithFormat:#"%#",[arrayButtonData objectAtIndex:indexPath.row]];
customCell.imageCircleRound.tag = indexPath.row;
NSLog(#"The custom cell button tag is - %ld",(long)customCell.imageCircleRound.tag);
NSLog(#"The label text is - %#",customCell.labelArrayListsNames.text);
[customCell.imageCircleRound addTarget:self action:#selector(cellCustomButtonClicked:)
forControlEvents:UIControlEventTouchUpInside];;
return customCell;
}
-(void)cellCustomButtonClicked:(UIButton *)sender
{
if(![sender isSelected])
{
[sender setBackgroundColor:[UIColor redColor]];
sender.Selected = YES;
}
else
{
[sender setBackgroundColor:[UIColor whiteColor]];
sender.Selected = NO;
}
}
It works fine.Check it.
enter code hereFor such problem use array of dictionary for tableview datasource array. Like this
NSMutableDictionary *datadict = [[NSMutableDictionary alloc] init];
[datadict setObject:#"Your title" forKey:#"Title"];
[datadict setObject:#"N" forKey:#"isSelected"];
[mainArray addObject: datadict]
put this code in loop for all your titles and N for isSelected key first time.
then you tableview method specially cellForRowAtIndexPath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *Cell = [MaintableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (Cell == nil)
{
Cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.textLabel.text = [[mainArray objectAtIndex:indexPath.row] objectForKey:#"Title"];
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.tag=indexPath.row;
[button addTarget:self
action:#selector(aMethod:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"" forState:UIControlStateNormal];
button.frame = CGRectMake(Cell.frame.size.width - 50, 10, 30, 30);
button.layer.cornerRadius = 60/2.0f;
button.layer.borderColor=[UIColor blackColor].CGColor;
if([[[mainArray objectAtIndex:indexPath.row] objectForKey:#"isSelected"] isEqualToString:#"Y"])
{
button.backgroundColor = [UIColor redColor];
}
else
{
button.backgroundColor = [UIColor whiteColor];
}
button.layer.borderWidth=2.0f;
//setting tag to button
button.tag=indexPath.row;
[Cell.contentView addSubview:button];
return Cell;
}
Then in your button action should be like
-(IBAction)aMethod :(id)sender
{
UIButton *selectedBtn = (UIButton *)sender;
if([[[mainArray objectAtIndex:[sender tag]] objectForKey:#"isSelected"] isEqualToString:#"Y"])
{
selectedBtn.backgroundColor = [UIColor whiteColor];
[[mainArray objectAtIndex:[sender tag]] removeObjectForKey:#"isSelected"];
[[mainArray objectAtIndex:[sender tag]] setObject:#"N" forKey:#"isSelected"];
}
else
{
selectedBtn.backgroundColor = [UIColor redColor];
[[mainArray objectAtIndex:[sender tag]] removeObjectForKey:#"isSelected"];
[[mainArray objectAtIndex:[sender tag]] setObject:#"Y" forKey:#"isSelected"];
}
}
you can also reload table in button action to see effect. It is good code technique to maintain multiple row selection and where data is large and realtime. By this we can get all selected rows whenever we needed on any event.

Adding last row cell (that is not part of sqlite table) on tableView

I have this issue on adding a last cell row to my tableView.
Can someone please tell me what's wrong with my code as the last row appears but it also appears elsewhere when the table is scrolled down. Any help will be greatly appreciated, Thank you. Here's my code:
#interface ViewOrderViewController : UIViewController < UITableViewDataSource, UITableViewDelegate> {
IBOutlet UITableView *tabView;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [appDelegate.vieworderArray count] + 1;
}
-(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:#"Cell"];
}
NSUInteger row = [indexPath row];
if(row == [appDelegate.vieworderArray count] ) {
cell.textLabel.text = [NSString stringWithFormat:#"extra cell"];
}else{
Vieworder *vieworderObj = (Vieworder *)[appDelegate.vieworderArray objectAtIndex:indexPath.row];
NSMutableString *mcmenuNameQuantity = [NSMutableString stringWithFormat:#"%# X %i", vieworderObj.mcmenu_name, vieworderObj.mcmenu_quantity];
UILabel *mcmenuLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 0, 200, 25)];
[mcmenuLabel setFont:[UIFont systemFontOfSize:13.0f]];
[mcmenuLabel setText:mcmenuNameQuantity];
UILabel *mcmenuPricexquantity = [[UILabel alloc] initWithFrame:CGRectMake(213, 0, 60, 25)];
[mcmenuPricexquantity setFont:[UIFont systemFontOfSize:12.0f]];
mcmenuPricexquantity.textAlignment = NSTextAlignmentRight;
NSMutableString *mcmenuPriceQuantityString = [NSMutableString stringWithFormat:#"%0.2f", vieworderObj.mcmenu_total_price];
mcmenuPricexquantity.numberOfLines = 2;
[mcmenuPricexquantity setText:mcmenuPriceQuantityString];
UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
deleteButton.frame = CGRectMake(12.0f, 0.0f, 25.0f, 25.0f);
deleteButton.tag = indexPath.row;
UIImage* imageDelete = [[UIImage alloc] init];
imageDelete = [UIImage imageNamed:[NSString stringWithFormat:#"vieworder_delete.png"]];
[deleteButton setImage:imageDelete forState:UIControlStateNormal]
[deleteButton addTarget:self action:#selector(performExpand:) forControlEvents:UIControlEventTouchUpInside];
UIButton *editButton = [UIButton buttonWithType:UIButtonTypeCustom];
editButton.frame = CGRectMake(280.0f, 0.0f, 25.0f, 25.0f);
UIImage* imageEdit = [[UIImage alloc] init];
imageEdit = [UIImage imageNamed:[NSString stringWithFormat:#"vieworder_edit.png"]];
[editButton setImage:imageEdit forState:UIControlStateNormal];
editButton.tag = indexPath.row;
[editButton addTarget:self action:#selector(buttonClicked2:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:deleteButton ];
[cell.contentView addSubview:mcmenuLabel];
[cell.contentView addSubview:mcmenuPricexquantity ];
[cell.contentView addSubview:editButton ];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}
return cell;
}
Use simplest code first
arr=#[#"A",#"B",#"C",#"D",#"E",#"F",#"A",#"B",#"C",#"D",#"E",#"F",#"A",#"B",#"C",#"D",#"E",#"F",#"A",#"B",#"C",#"D",#"E",#"F",#"A",#"B",#"C",#"D",#"E",#"F",#"A",#"B",#"C",#"D",#"E",#"F"];
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arr count]+1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
cell.textLabel.text=(indexPath.row==arr.count)?#"End of Row":arr[indexPath.row];
return cell;
}
If it is working then then there should be some problem with your else condition where you are adding multiple subviews to cell.ContentView.

How to add images to UITableView cell?

I temporarly added some values to the UITableViewCell programmatically. But I need to add images to each cell. How can I do that?
Here is my code. .h file
#interface BidalertsViewController : UIViewController <UITableViewDelegate,UITableViewDataSource> {
NSArray *listData;
}
#property(nonatomic, retain) NSArray *listData;
#end
.m file
#synthesize listData;
- (void)viewDidLoad {
UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(5,0,310,28)];
newView.backgroundColor=[UIColor whiteColor];
UITextView *mytext = [[UITextView alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 25.0)];
mytext.backgroundColor = [UIColor clearColor];
mytext.textColor = [UIColor blackColor];
mytext.editable = NO;
mytext.font = [UIFont systemFontOfSize:15];
mytext.text = #"Asset Name";
[mytext release];
[newView addSubview:mytext];
[self.view addSubview:newView];
[newView release];
NSArray *array = [[NSArray alloc] initWithObjects:#"iPhone", #"iPod", #"iPad",nil];
self.listData = array;
[array release];
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)dealloc {
[listData dealloc];
[super dealloc];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if (cell == nil) { cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
return cell;
UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:#"user.jpg"];
[cell.contentView addSubview:imv];
[imv release];
}
#end
The code didn't add images to the cell. What's the problem? How can I do to add custom image to cell?
Move return cell; at the end of the method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if (cell == nil) { cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:#"user.jpg"];
[cell.contentView addSubview:imv];
[imv release];
return cell;
}
You can add images using the imageView property of a cell:
cell.imageView.image = [UIImage imageNamed:#"user.jpg"];
in your - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath method.
Here's an example cell loading a facebook image in a table cell.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
// Leave cells empty if there's no data yet
if (nodeCount > 0)
{
// Set up the cell...
AppRecord *appRecord = [self.friendsList objectAtIndex:indexPath.row];
cell.textLabel.text = friend.name;
// Only load cached images; defer new downloads until scrolling ends
if (!appRecord.icon)
{
// set the url
appRecord.imageURLString = [NSString stringWithFormat:#"http://graph.facebook.com/%#/picture", friend.recordID];
// request the download
if (self.tableView.dragging == NO && self.tableView.decelerating == NO)
{
[self startIconDownload:appRecord forIndexPath:indexPath];
}
// if a download is deferred or in progress, return a placeholder image
cell.imageView.image = [UIImage imageNamed:#"Placeholder.png"];
}
else
{
cell.imageView.image = appRecord.icon;
}
}
return cell;
you adding it right, but you fogot one thing:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if (cell == nil) { cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
}
NSUInteger row = [indexPath row]; cell.textLabel.text = [listData objectAtIndex:row];
UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:#"user.jpg"];
[cell.contentView addSubview:imv];
[imv release];
//you fogot this:
return cell;
}
// create a rectangle box for image view
UIImageView *iconImage = [[UIImageView alloc] init];
iconImage.frame = CGRectMake(12,4,53.5,53.5);
// Create a label for cells
UILabel *cellName = [[UILabel alloc] initWithFrame:CGRectMake(75,18,200,20)];
cellName.font = [self fontForBodyTextStyle];
NSString *cellNameStr = [NSString stringWithFormat:#"%#",self.tableCellNames[indexPath.row]];
// Select path row tab actions
switch (indexPath.row) {
case 0:
cellName.text = cellNameStr;
iconImage.image = [UIImage imageNamed:#"condition.png"];
[cell.contentView addSubview:iconImage];
[cell.contentView addSubview:cellName];
break;
case 1:
cellName.text = cellNameStr;
iconImage.image = [UIImage imageNamed:#"videos.png"];
[cell.contentView addSubview:iconImage];
[cell.contentView addSubview:cellName];
break;
case 2:
cellName.text = cellNameStr;
iconImage.image = [UIImage imageNamed:#"provider.png"];
[cell.contentView addSubview:iconImage];
[cell.contentView addSubview:cellName];
break;
case 3:
cellName.text = cellNameStr;
iconImage.image = [UIImage imageNamed:#"info.png"];
[cell.contentView addSubview:iconImage];
[cell.contentView addSubview:cellName];
break;
default:
NSAssert(NO, #"Unhandled value in cellForRowAtIndexPath");
break;
}
Thank VKJ,

Resources