After trying various options, and reading numerous answers on SO, I am posting this question hoping somebody can provide some insight or a solution to this problem:
iOS5.1, XCode 4.4.1, Storyboard, ARC
I have a "Grouped" tableview, with each cell containing bunch of labels, images and buttons. One of the label, Description label, for it the text can be large or small, which means if text is large I have to increase the size of the label accordingly and place the buttons below accordingly as well. I am able to do all this, but the problem is that buttons appears twice when I scroll past the first cell and keeps repeating as I scroll.
Here's the code, all I am doing is calculating the height of label based on text, resizing the label, and then placing the 3 buttons below the description label accordingly.
The code below is just for one button but this should give the idea of what i am doing. I have tried to do similar stuff in "willDisplayCell", in the custom cell class but still the 3 buttons keeps repeating when i scroll down in the tableview. PLease refer the screenshot, the first three buttons shouldn't even show.
I noticed that position of first 3 buttons is same as if it ignores the sizeIncrement, meaning "359.0f + sizeIncrement +20" minus the "sizeIncrement", "sizeIncrement"= the height of description label after calculation
I also noticed that if i do
float y = 359.0f + 20;
instead of this
float y = 359.0f + sizeIncrement +20;
the repetition of Buttons problem is gone.
P.S: I know this is not the best code, but I have been trying lot of stuff to solve the problem so not bothered with best practices etc at this point.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"tipsid";
TipsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[TipsCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
id tip = [_tips objectAtIndex: [indexPath section]];
NSDictionary *tipForIndex = [_tips objectAtIndex: [indexPath section]];
float sizeIncrement = [Utility getLabelHeightForText:[tipForIndex objectForKey:@"tipDescripion"]
withWidth:285.0f
withFont:[UIFont systemFontOfSize:14.0f]];
// Here I Resize the Label, code below to create a button and position accordingly.
float y = 359.0f + sizeIncrement +20;
UIButton *likeButton = [[UIButton alloc] initWithFrame:CGRectMake(10, y, 80, 26)];
likeButton.tag = [indexPath section];
// add targets and actions
[likeButton addTarget:self action:@selector(likebuttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[likeButton setBackgroundImage:[UIImage imageNamed:@"likebutton.png"] forState:UIControlStateNormal];
[likeButton setImage:[UIImage imageNamed:@"likedButton.png"] forState:UIControlStateSelected];
// add to a view
[cell.contentView addSubview:likeButton];
.....similarly create 2 other buttons