UISwitch off state is not stable while scrolling in tableview - ios

I'm creating a UISwitch programmatically in one of the tableview datasource function(cell for row at index). when I'm scrolling the table view, the OFF state switches are malfunctioned(UI) two rounds appeared. Attaching the screenshot of the switch.
Appreciate your help!
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
UILabel *title = (UILabel*)[cell viewWithTag:80];
UILabel *description = (UILabel*)[cell viewWithTag:81];
UIView *innerView = (UIView *)[cell viewWithTag:82];
innerView.layer.borderColor=[[UIColor colorWithRed:229/255.0f green:229/255.0f blue:229/255.0f alpha:1.0] CGColor];
innerView.layer.borderWidth = 2.0f;
NSDictionary *displayDict = scenarioListsArray[indexPath.row];
title.text =[displayDict objectForKey:#"name"];
description.text = [displayDict objectForKey:#"description"];
UISwitch *myswitch = [[UISwitch alloc]initWithFrame:CGRectMake(cell.contentView.frame.size.width-60, (cell.contentView.frame.size.height/2)-20 , 100, 100)];
myswitch.onTintColor = [UIColor colorWithRed:25/255.0f green:122/255.0f blue:66/255.0f alpha:1];
[cell.contentView addSubview:myswitch];
myswitch.tag = indexPath.row;
[myswitch addTarget:self action:#selector(cellButtonClickAction:) forControlEvents:UIControlEventValueChanged];
if ([[displayDict objectForKey:#"status"] isEqualToString:#"ACTIVE"]) {
[myswitch setOn:YES animated:YES];
}
else
{
[myswitch setOn:NO animated:YES];
}
return cell;
}

I have faced the same issue and fixed with following code before creating switch
for(UIView *subView in cell. contentView.subviews){
if ([subView isKindOfClass:[UISwitch class]]) {
[subView removeFromSuperview];
}
}
Or
static NSString *TableIdentifier = #"YourCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableIdentifier];
//place your all UI elements code here.
}

I have updated your code, try this will work for you,
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
UILabel *title = (UILabel*)[cell viewWithTag:80];
UILabel *description = (UILabel*)[cell viewWithTag:81];
UIView *innerView = (UIView *)[cell viewWithTag:82];
innerView.layer.borderColor=[[UIColor colorWithRed:229/255.0f green:229/255.0f blue:229/255.0f alpha:1.0] CGColor];
innerView.layer.borderWidth = 2.0f;
NSDictionary *displayDict = scenarioListsArray[indexPath.row];
title.text =[displayDict objectForKey:#"name"];
description.text = [displayDict objectForKey:#"description"];
UISwitch *myswitch = [cell.contentView viewWithTag:indexPath.row+597];
if(mySwitch == nil){
myswitch = [[UISwitch alloc]initWithFrame:CGRectMake(cell.contentView.frame.size.width-60,(cell.contentView.frame.size.height/2)-20 , 100, 100)];
[cell.contentView addSubview:myswitch];
[myswitch addTarget:self action:#selector(cellButtonClickAction:) forControlEvents:UIControlEventValueChanged];
}
myswitch.onTintColor = [UIColor colorWithRed:25/255.0f green:122/255.0f blue:66/255.0f alpha:1];
myswitch.tag = indexPath.row+597; //597 is extra number added to tag
if ([[displayDict objectForKey:#"status"] isEqualToString:#"ACTIVE"]) {
[myswitch setOn:YES animated:YES];
}
else
{
[myswitch setOn:NO animated:YES];
}
return cell;
}

Related

Radio Button issue in Objective c

I have a table view in which I'm loading some data i'm trying to make radio button on that data, but when i select any cell it does not deselect other it is working as a check box . I'm confused where i'm doing mistake, My code is 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];
radiobtn = [UIButton buttonWithType:UIButtonTypeCustom];
radiobtn.frame = CGRectMake(30, 60, 30, 30);
[radiobtn setImage:[UIImage imageNamed:#"circle.png"] forState:UIControlStateNormal];
[radiobtn setImage:[UIImage imageNamed:#"rights.png"] forState:UIControlStateSelected];
[radiobtn addTarget:self action:#selector(radiobtn:)
forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = radiobtn;
}
cell.textLabel.text = [dataArray objectAtIndex:indexPath.row];
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.font = [UIFont boldSystemFontOfSize:17];
UIView *selectionColor = [[UIView alloc] init];
selectionColor.backgroundColor = [UIColor colorWithRed:(0) green:(0) blue:(0) alpha:1];
cell.selectedBackgroundView = selectionColor;
cell.selectionStyle = UITableViewCellDragStateLifting;
return cell;
}
-(void)radiobtn:(UIButton *)sender
{
if([sender isSelected])
{
[sender setSelected:NO];
}
else
{
[sender setSelected:YES];
}
}
It is looking like this,
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 *radiobtn = [UIButton buttonWithType:UIButtonTypeCustom];
radiobtn.frame = CGRectMake(30, 60, 30, 30);
radiobtn.userInteractionEnabled = NO;
[radiobtn setImage:[UIImage imageNamed:#"circle.png"] forState:UIControlStateNormal];
[radiobtn setImage:[UIImage imageNamed:#"rights.png"] forState:UIControlStateSelected];
// [radiobtn addTarget:self action:#selector(radiobtn:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = radiobtn;
}
cell.textLabel.text = [dataArray objectAtIndex:indexPath.row];
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.font = [UIFont boldSystemFontOfSize:17];
UIView *selectionColor = [[UIView alloc] init];
selectionColor.backgroundColor = [UIColor colorWithRed:(0) green:(0) blue:(0) alpha:1];
cell.selectedBackgroundView = selectionColor;
cell.selectionStyle = UITableViewCellDragStateLifting;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIButton *button = (UIButton *)cell.accessoryView;
button.selected = YES;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIButton *button = (UIButton *)cell.accessoryView;
button.selected = NO;
}

UISwitch state is not updated while scrolling

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
UISwitch *clickButton = (UISwitch *)[cell viewWithTag:30];
clickButton.tag = indexPath.row;
[clickButton addTarget:self action:#selector(cellButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
UILabel *title = (UILabel*)[cell viewWithTag:80];
UILabel *description = (UILabel*)[cell viewWithTag:81];
UIView *innerView = (UIView *)[cell viewWithTag:82];
innerView.layer.borderColor=[[UIColor colorWithRed:229/255.0f green:229/255.0f blue:229/255.0f alpha:1.0] CGColor];
innerView.layer.borderWidth = 2.0f;
NSDictionary *displayDict = scenarioListsArray[indexPath.row];
title.text =[displayDict objectForKey:#"name"];
description.text = [displayDict objectForKey:#"description"];
if ([[displayDict objectForKey:#"status"] isEqualToString:#"ACTIVE"]) {
[clickButton setOn:YES animated:YES];
NSLog(#"SWITCH %ld",clickButton.tag);
}
else
{
[clickButton setOn:NO animated:YES];
}
i need to change the state of Switch depends on Array but switch state not change on array.

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.

Selecting a cell shows a button and deselecting hides the button

I want a button to show when i select a cell, when i select the same cell or another cell i want the button to hide. So one button should only be visible at a time.
What i have:
in my .h file:
#property (strong, nonatomic) NSIndexPath *isselectednow;
and my .m file:
Viewdidload:
self.isselectednow = [NSIndexPath indexPathForRow:7 inSection:1];
cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//[cell addSubview:[self drawSeparationView:(indexPath.row)]];
UILabel *DateName = (UILabel *)[cell viewWithTag:100100];
DateName.textColor = [UIColor blackColor];
//DateName.text = [NSString stringWithFormat:#"%ld",(long)indexPath.row ];
DateName.text = objects[indexPath.row];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(buttonOnCellPressed:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Update" forState:UIControlStateNormal];
button.frame = CGRectMake(DEVICE_SIZE.width - 60, 18, 55, 15);
[cell addSubview:button];
if ([indexPath compare:self.isselectednow] == NSOrderedSame) {
button.hidden = NO;
}
else{
button.hidden = YES;
}
UILabel *lbl1 = (UILabel *)[cell viewWithTag:100101];
lbl1.textColor = UIColorFromRGB(0x141414);
UILabel *lbl2 = (UILabel *)[cell viewWithTag:100102];
lbl2.textColor = UIColorFromRGB(0x141414);
UILabel *lbl3 = (UILabel *)[cell viewWithTag:100103];
lbl3.textColor = UIColorFromRGB(0x141414);
UILabel *lbl4 = (UILabel *)[cell viewWithTag:100104];
lbl4.textColor = UIColorFromRGB(0x141414);
UILabel *lbl5 = (UILabel *)[cell viewWithTag:100105];
lbl5.textColor = UIColorFromRGB(0x141414);
UITextField *breakfastName = (UITextField *) [cell viewWithTag:100200];
breakfastName.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:#"Name here"
attributes:#{NSForegroundColorAttributeName:UIColorFromRGB(0x141414)}];
breakfastName.textColor = UIColorFromRGB(0x141414);
[breakfastName setDelegate:self];
//[breakfastName addTarget:self action:#selector(textChanged:) forControlEvents:UIControlEventEditingChanged];
UITextField *OutName = (UITextField *) [cell viewWithTag:100201];
OutName.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:#"Name here"
attributes:#{NSForegroundColorAttributeName:UIColorFromRGB(0x141414)}];
OutName.textColor = UIColorFromRGB(0x141414);
[OutName setDelegate:self];
UITextField *lunchName = (UITextField *) [cell viewWithTag:100202];
lunchName.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:#"Name here"
attributes:#{NSForegroundColorAttributeName:UIColorFromRGB(0x141414)}];
lunchName.textColor = UIColorFromRGB(0x141414);
[lunchName setDelegate:self];
UITextField *InName = (UITextField *) [cell viewWithTag:100203];
InName.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:#"Name here"
attributes:#{NSForegroundColorAttributeName:UIColorFromRGB(0x141414)}];
InName.textColor = UIColorFromRGB(0x141414);
[InName setDelegate:self];
UITextField *eveningName = (UITextField *) [cell viewWithTag:100204];
eveningName.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:#"Name here"
attributes:#{NSForegroundColorAttributeName:UIColorFromRGB(0x141414)}];
eveningName.textColor = UIColorFromRGB(0x141414);
[eveningName setDelegate:self];
UITextField *othersName = (UITextField *) [cell viewWithTag:100205];
othersName.attributedPlaceholder =
[[NSAttributedString alloc]
initWithString:#"Name here"
attributes:#{NSForegroundColorAttributeName:UIColorFromRGB(0x141414)}];
othersName.textColor = UIColorFromRGB(0x141414);
cell.clipsToBounds = YES;
cell.accessoryType = UITableViewCellAccessoryNone;
cell.backgroundColor = UIColorFromRGB(0xf3f0e9);
return cell;
}
didSelectRowAtIndexPath:
[tableView beginUpdates];
if ([indexPath compare:self.isselectednow] == NSOrderedSame) {
self.isselectednow = nil;
}
else{
self.isselectednow = indexPath;
}
[tableView endUpdates];
//[tableView reloadData];
From the docs about beginUpdates:
Call this method if you want subsequent insertions, deletion, and selection operations (for example, cellForRowAtIndexPath: and indexPathsForVisibleRows) to be animated simultaneously.
Although you've changed the isSelectedNow boolean, you haven't actually specified any insertion, deletion, or selection operations between beginUpdates and endUpdates. So you're not actually beginning or ending any updates to the cells' content with that code.
I'm not sure what you're trying to do, but taking out [tableView beginUpdates]; and [tableView beginUpdates]; and reinserting [tableView reloadData]; would result in a proper data reload.
Edit:
Aside from that, the problem is that you're reusing your cells with dequeueReusableCellWithIdentifier:, but you're adding a new UIButton subview each time, so you're basically putting each new UIButton over the old. I suggest doing what you've done for all your labels and textfields in cellForRowAtIndexPath: -- reuse your update button by adding it to your custom table view cell and accessing it with viewWithTag:.

UITableView can not show correct color of button in iOS

I used BVReorderTableView https://github.com/bvogelzang/BVReorderTableView to reorder row in tableview. But i have a problem: When I add UIButton to each row, this button always show clear color.Once selected row, this button just shown.
I tried this code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIButton *prioritybtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[prioritybtn setFrame:CGRectMake(220, 0, 70, 32)];
[prioritybtn setTag:4000];
[cell.contentView addSubview:prioritybtn];
}
UIButton *priorityButton = (UIButton*)[cell.contentView viewWithTag:4000];
if ([[items objectAtIndex:indexPath.row] isKindOfClass:[NSString class]] &&
[[items objectAtIndex:indexPath.row] isEqualToString:#"DUMMY"]) {
cell.textLabel.text = #"";
cell.contentView.backgroundColor = [UIColor clearColor];
prioritybtn.hidden= YES;
}
else {
cell.textLabel.text = [items objectAtIndex:indexPath.row];
[priorityButton setSelected:NO];
[priorityButton setTitle:#"Priority" forState:UIControlStateNormal];
priorityButton.enabled = YES;
}
return cell;
}
Also, I want to hide button only at first row, other row is still shown. How can i do that? Thanks
To hide the button at first row:
if (indexPath.row == 1){
prioritybtn.hidden = YES;
prioritybtn.userInteractionEnabled = NO;
} else {
prioritybtn.hidden = NO;
prioritybtn.userInteractionEnabled = YES;
}
Add this before return cell;
Regarding the color, add this where you initialize the button:
UIButton *prioritybtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
prioritybtn.backgroundColor = [UIColor greenColor]; //put the color you want
Try like this:-
cell.selectionStyle =
UITableViewCellSelectionStyleNone;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
UIButton *reletedbtn=nil;
UILabel *Nameoflb=nil;
cell = [tableeample dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Nameoflb = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,40)];
Nameoflb.backgroundColor=[UIColor clearColor];
Nameoflb.textAlignment=NSTextAlignmentCenter;
Nameoflb.textColor=[UIColor blackColor];
[Nameoflb setFont:[UIFont fontWithName:#"Helvetica-Bold" size :14]];
Nameoflb.text=[dataarray objectAtIndex:indexPath.row];
[[cell contentView] addSubview:Nameoflb];
if (indexPath.row!=0)
{
reletedbtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
reletedbtn.frame=CGRectMake(Nameoflb.frame.origin.x+Nameoflb.frame.size.width, Nameoflb.frame.origin.y+10,40, 25);
reletedbtn.tintColor=[UIColor redColor];
[reletedbtn setTitle:#"butoon" forState:UIControlStateNormal];
//[reletedbtn addTarget:self action:#selector(statusMasseage:) forControlEvents:UIControlEventTouchUpInside];
//reletedbtn.tag=1;
[[cell contentView] addSubview:reletedbtn];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}

Resources