UITableview not updating uitableviewcell custom cell from storyboard - ios

I have tried as many as solution I found to resolve this problem.
My latest code is show blow:
static NSString *simpleTableIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
[[cell viewWithTag:1000] removeFromSuperview];
[[cell viewWithTag:2000] removeFromSuperview];
// other code for setting view that works perfect then
if(some condition){
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:#"upgrey.png"] forState:UIControlStateNormal];
btn.frame=upButton.frame;
[btn addTarget:self action:#selector(upButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:btn];
UIButton *btn2=[UIButton buttonWithType:UIButtonTypeCustom];
[btn2 setImage:[UIImage imageNamed:#"downgrey.png"] forState:UIControlStateNormal];
btn2.frame=downButton.frame;
[btn2 addTarget:self action:#selector(downButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:btn2];
btn.tag=1000;
btn2.tag=2000;
}
return cell;
but this does not work. if i add
[[cell viewWithTag:1000] removeFromSuperview];
[[cell viewWithTag:2000] removeFromSuperview];
in start it remove buttons from all cells. and if i do not use this. it shows all cells with these two buttons.
thanks in advance.

Even though you've already accepted your own answer, I'll take a moment to explain why you had that issue and how you can better structure your UITableViews in the future.
The reason why "it shows all cells with these two buttons" when you don't have those removeFromSubview lines is because by implementing dequeueReusableCellWithIdentifier:, you're reusing your cells and the contents thereof. Repeatedly adding the same subview during each call of cellForRowAtIndexPath makes the fact that you're reusing the cells completely pointless since you're reusing absolutely nothing within them. So either, don't reuse your cells at all or, better yet since each cell's contents are exactly the same, do reuse your cells and also reuse those buttons.
There are two good ways to do this. One way to do this is to create a UITableViewCell custom subclass. But since your cells' contents are fairly simple and you say your else conditional's already functional, I'll suggest a different way that might be a bit less code-intensive. Here's my suggestion:
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Create two identifiers -- one for "some condition" one
// for the "other condition"
static NSString *simpleTableIdentifier1 = #"cell1";
static NSString *simpleTableIdentifier2 = #"cell2";
if (some condition) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier1];
// Only add the buttons when cell == nil, i.e. during the first
// time cell's initialized to hold a UITableViewCell
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier1]
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:#"upgrey.png"] forState:UIControlStateNormal];
btn.frame=upButton.frame;
[btn addTarget:self action:#selector(upButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:btn];
UIButton *btn2=[UIButton buttonWithType:UIButtonTypeCustom];
[btn2 setImage:[UIImage imageNamed:#"downgrey.png"] forState:UIControlStateNormal];
btn2.frame=downButton.frame;
[btn2 addTarget:self action:#selector(downButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:btn2];
}
} else {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier2];
if (cell == nil) {
....

Related

iOS Custom Cell - Reuse identifier

I am trying to create a custom cell with favorite button on it. Its working fine but I think reuse identifier is creating problem here. I have tried it in two ways and it is working fine in both.
Here is my first try:
When I am selecting the button, it is changing to yellow button and vice -versa. But after scrolling up or down,it is changing to its normal state again. Why?
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CI=#"CELL";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CI];
if(!cell) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CI];
}
favbtn=[[UIButton alloc]initWithFrame:CGRectMake(160, 10, 30, 35)];
[cell.contentView addSubview:favbtn];
[favbtn setBackgroundImage:[UIImage imageNamed:#"starr.png"] forState:UIControlStateNormal];
[favbtn addTarget:self action:#selector(fav:) forControlEvents:UIControlEventTouchUpInside];
cell.textLabel.text=[favdata objectAtIndex:indexPath.row];
return cell;
}
-(void)fav:(id)sender
{
if ([sender isSelected]) {
[sender setImage:[UIImage imageNamed:#"starr.png"] forState:UIControlStateNormal];
[sender setSelected:NO];
} else {
[sender setImage:[UIImage imageNamed:#"star.png"] forState:UIControlStateSelected];
[sender setSelected:YES];
}
}
Here is my second try:
Here every sixth cell is showing the same state.
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CI=#"CELL";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CI];
if(!cell) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CI];
favbtn=[[UIButton alloc]initWithFrame:CGRectMake(160, 10, 30, 35)];
[cell.contentView addSubview:favbtn];
[favbtn setBackgroundImage:[UIImage imageNamed:#"starr.png"] forState:UIControlStateNormal];
[favbtn addTarget:self action:#selector(fav:) forControlEvents:UIControlEventTouchUpInside];
cell.textLabel.text=[favdata objectAtIndex:indexPath.row];
}
return cell;
}
First of all modify this methods:
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CI=#"CELL";
UIButton * favbtn;
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CI];
if(!cell)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CI];
favbtn=[[UIButton alloc]initWithFrame:CGRectMake(160, 10, 30, 35)];
[cell.contentView addSubview:favbtn];
[favbtn setTag:11221133];
}
favbtn = [cell.contentView viewWithTag:11221133];
[favbtn setBackgroundImage:[UIImage imageNamed:#"starr.png"] forState:UIControlStateNormal];
[favbtn setImage:[UIImage imageNamed:#"starr.png"] forState:UIControlStateNormal];
[favbtn setImage:[UIImage imageNamed:#"star.png"] forState: UIControlStateSelected];
//Check selections here and if this index is selected make btn selected.
[favbtn addTarget:self action:#selector(fav:) forControlEvents:UIControlEventTouchUpInside];
cell.textLabel.text=[favdata objectAtIndex:indexPath.row];
cell.contentView.tag = indexPath.row;
return cell;
}
-(void)fav:(id)sender
{
UIButton * btn = (UIButton *)sender;
btn.selected = !btn.selected;
int index = [[btn superview] tag]; // use this index for storing selections
}
Then make a array for storing selections. Compare this selection in cellForRowAtIndexPath and make btn selected or not selected.
Hope this will help you.....
You need to understand the way the cell is being reused. When your cell is scrolled out of the screen, it will be reused for the cell that is entering the screen. Table view will keep calling the method cellForRowAtIndexPath every time they want to render the cell. In your code, you init a new favbtn all the time, so even if the cell already contains it and being reused, you will keep on adding more buttons into it. Here's my suggestions:
Create your own subclass of UITableViewCell. Let's say FavoriteCell. Put all your code to add the favorite button inside your subclass.
In ViewDidLoad register your cell with your table view. Something like this: [self.tableView registerClass:...] or [self.tableView registerNib:...] depending on if you have a nib file for your cell or not.
In cellForRowAtIndexPath, dequeue your cell as usual but you don't have to check if it's nil or not, and you don't have to create the favorite button since you already put it inside your subclass.
Just remember that, the method cellForRowAtIndexPath will be called all the time so your logic of inserting favorite button has to be done properly. Make sure that you only insert it once and update its property properly.

UIButton of UITableViewCell disappear on scroll

I Have a problem with my custom UItableViewCell. It's seems that all UIButton of UITableViewCell disappear on scroll. Specilay on my 25 cell. Any one have any idea ?
any help would be appreciated :)
That some code :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString* cellIdentifier = #"Cell";
Cell * __strong cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell){
cell = [[Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
InfoObject __weak *obj = [_pos objectAtIndex:indexPath.row];
[cell configCell];
cell.id = obj.id;
{// EVENT ON BUTTON
[cell.checkbox addTarget:self action:#selector(checkup:) forControlEvents:UIControlEventTouchUpInside];
[cell.btnPaymentState addTarget:self action:#selector(changePaymentState:) forControlEvents:UIControlEventTouchUpInside];
}
{// SET BUTTON CHECKBOX
cell.checkbox.tag = indexPath.row;
[cell.checkbox setImage:[UIImage imageNamed:IMG_BLACK_UNCHECKBOX] forState:UIControlStateNormal];
[cell.checkbox setImage:[UIImage imageNamed:IMG_BLACK_CHECKBOX] forState:UIControlStateSelected];
[cell.checkbox setImage:[UIImage imageNamed:IMG_BLACK_CHECKBOX] forState:UIControlStateHighlighted];
}
{// SET BUTTON PAYMENT STATE
cell.btnPaymentState.tag = indexPath.row;
[cell.btnPaymentState setImage:[self getImageAssociateWithName:obj.stringPaymentState] forState:UIControlStateNormal];
[cell.btnPaymentState setImage:[self getImageAssociateWithName:obj.stringPaymentState] forState:UIControlStateSelected];
[cell.btnPaymentState setImage:[self getImageAssociateWithName:obj.stringPaymentState] forState:UIControlStateHighlighted];
}
[self SetSelectedBackgroundColorSelectedForFolderCellAtRow:indexPath.row
:obj.selected Cell: cell];
[cell.checkbox setSelected:obj.selected];
[self setCellColorTextOfObjectPrepare:cell withObj:obj];
return cell;
}
I solve my problem. The problem is that i was using Tag for my UIButton and the identifier was the same number tag of another UIView so when i was removing my UIView the UIButton disappear also. Thanks all for your answer.
Remove if (!cell)
And you're good to go.

Differentiate button and row click event in Table View

In my Application in UITableView i put UIButton in every cell.
but when i click on Button then some times button event will come and some time Cell's Row clicked.
I need to get button click event all the time when button click and row click event when row clicked.
How to come over this issue ?
All the Row are identical (means i didn't use reusable).
My code for this is...
- (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:#"Cell1"];
[cell clearsContextBeforeDrawing];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(5,220,70, 30);
[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
[btn setTitle:[NSString stringWithFormat:#"button == %ld",(long)indexPath.row] forState:UIControlStateNormal];
btn.tag = indexPath.row;
[btn addTarget:self action:#selector(methodOfButton:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btn];
}
return cell;
}
Any tutorial, code, link will be great help.
Most likely the problem you're seeing happen when user tapped close to the button but not on it. In other interface elements you will not notice this, since no other event will be generated but in your cases 'didSelectRow' will fire.
You need to make sure button occupies as much room as possible on the cell (at least full cell height). This way you will get user less chance to miss tap. Right now your button is only 30px tall, what the height of the cell?

UIButton Image Changing In Multiple UITableViewCells

I am currently building an iOS app that uses a UITableView with custom UITableViewCells that include a button. What I want to accomplish is having the UIButton's image change on touch up inside. That part is working fine, the issue is when you scroll, suddenly every few row buttons located in the UITableViewCell have this new image. Below is some of my code. Any help would be appreciated.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cellID = #"CellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
//YEP BUT
yepBut = [[UIButton alloc] initWithFrame:CGRectMake(23, 16, 64, 32.5)];
[yepBut addTarget:self action:#selector(yepPost:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:yepBut];
}
[yepBut setImage:[UIImage imageNamed:#"yepBtn"] forState:UIControlStateNormal];
return cell;
}
-(void) yepPost:(id) sender{
//UIButton *clicked = (UIButton *) sender;
[sender setImage:[UIImage imageNamed:#"yepBtnACT"] forState:UIControlStateNormal];
}
Thanks!
You need to have a property that you set when the button is touched that you check in cellForRowAtIndexPath. So, in the button's method, have a property, say lastTouched (#property (strong,nonatomic) NSIndexPath *lastTouched, or NSInteger if you don't have sections), that you set to the indexPath (or indexPath.row) of the cell in which the touched button resided (gotten from the cell which you get by searching up through the superviews of the button until you find the cell, or by using tags on your buttons equal to the indexPath.row). After that, you have to reloadData or reloadRowsAtIndexPaths to make the change happen. In cellForRowAtIndexPath, you would set your images like this:
if ([self.lastTouched isEqual:indexPath]) {
[yepBut setImage:[UIImage imageNamed:#"yepBtnACT"] forState:UIControlStateNormal];
else{
[yepBut setImage:[UIImage imageNamed:#"yepBtn"] forState:UIControlStateNormal];
}
When you first initialize lastTouched, you want to set it to an indexPath that doesn't occur in your table, so nothing will have the yepButAct image until you touch one.
Subclassing UITableViewCell fixed my issue.

Two UITableViewCell have the same indexPath?

I have a problem like this:
I have a table view. when i click on a cell (or row), the cell will add 2 more buttons and re-size.
This function it work fine!
The problem is when i click first row,
it creates 2 buttons and re-size
and then scroll down, another cell also display 2 buttons.
and this is my code for function of displaying button and resizing cell
I believe when scrolling down the table is reloaded and reset the indexPath, so 2 cells both display the buttons.
Anyone has any suggestion!?
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
tvcCategory *cell = (tvcCategory*)[tableView cellForRowAtIndexPath:indexPath];
NSLog(#"- %i ", indexPath.item);
if (selectedIndex.item != indexPath.item) {
[btnEdit removeFromSuperview];
[btnTransact removeFromSuperview];
objSession.catId = cell.lblId.text;
btnEdit = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnEdit.frame = CGRectMake(91, 72, 73, 35);
[btnEdit setTitle:#"Edit" forState:UIControlStateNormal];
[btnEdit setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btnEdit setBackgroundImage:buttonImage forState:UIControlStateNormal];
[btnEdit setBackgroundImage:buttonImageHighlight forState:UIControlStateHighlighted];
[btnEdit addTarget:self action:#selector(moveToEditingScreen) forControlEvents:UIControlEventTouchUpInside];
btnTransact = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnTransact.frame = CGRectMake(176, 72, 95, 35);
[btnTransact setTitle:#"Transact" forState:UIControlStateNormal];
[btnTransact setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[btnTransact setBackgroundImage:buttonImage forState:UIControlStateNormal];
[btnTransact setBackgroundImage:buttonImageHighlight forState:UIControlStateHighlighted];
[btnTransact addTarget:self action:#selector(moveToTransactionScreen) forControlEvents:UIControlEventTouchUpInside];
[tableView reloadData];
[cell.contentView addSubview:btnEdit];
[cell.contentView addSubview:btnTransact];
lastClickedCell = cell;
self.selectedIndex = indexPath;
NSIndexPath* rowToReload = [NSIndexPath indexPathForRow:-1 inSection:0];
NSArray* rowsToReload = [NSArray arrayWithObjects:rowToReload, nil];
[tableView reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationFade];
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
[tableView reloadData];
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
}
}
I really appreciate
The problem that you are facing, like the guys has had exposed in the comments is that in the table view method you need to reuse cells to optimize the performance, so you need to take this cells that are already used and adjust it to your expected cell state.
Probably in your cellForRowAtIndexPath you are just taking care to allocate it and adjust it when you do not have a cell, you will need to adjust it, you have some options, like always adjust it to the initial state or you can check if the buttons are showed and only in this cases redesign your cell.
So in your class, at some point you have this method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
} else {
if([selectedIndex isEqual:indexPath]){
//Add your buttons and adjust the cell to show the extra buttons
} else {
if(your selected index isn't in the screen anymore){
[btnEdit removeFromSuperview];
[btnTransact removeFromSuperview];
}
//your others adjusts
}
}
}
EDIT:
[[yourTable indexPathsForVisibleRows] containsObject:selectedIndexPath];
This method return an array that you need to check if your selectedindex is inside it.
More about UITableView you can found at the documentation.

Resources