Muhammad Anum
Muhammad Anum

Reputation: 136

UITableView Strange Behavior while scrolling

Below is my code.

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellTwo" forIndexPath:indexPath]; 
UILabel * name = (UILabel *)[cell viewWithTag:4];
UILabel * age = (UILabel *)[cell viewWithTag:5];
UILabel * city = (UILabel *)[cell viewWithTag:6];

NSString * currentDate = self.calenderDates[indexPath.section];
NSArray * dicDate = [self.dataDictionay valueForKey:currentDate];

UIButton * checkinBtn = (UIButton*)[cell viewWithTag:9];
UIButton * checkoutBtn = (UIButton*)[cell viewWithTag:10];

checkinBtn.tag = indexPath.row;
checkoutBtn.tag = indexPath.row;

NSString * papikDate = [dicDate[indexPath.row] valueForKey:@"strat_date"];

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSString * todayDate = [dateFormat stringFromDate:[NSDate date]];

if ([papikDate isEqualToString:todayDate]) {
    [checkinBtn setHidden:NO];
    [checkinBtn setHidden:NO];
} else {  
    [checkinBtn setHidden:YES];
    [checkinBtn setHidden:YES];
}

While scrolling tableview " if condition " do satisfy but buttons dont hides. what i wanted to do is that if, current date and date in API matches button appear else button remains hidden.

Upvotes: 1

Views: 40

Answers (1)

luk2302
luk2302

Reputation: 57114

The following code will cause major problems:

UIButton * checkinBtn = (UIButton*)[cell viewWithTag:9];
UIButton * checkoutBtn = (UIButton*)[cell viewWithTag:10];

checkinBtn.tag = indexPath.row;
checkoutBtn.tag = indexPath.row;

That works for the first time you use the cell, as soon as you resuse the cell, the tags will no longer match and you will not retrieve the actual button. If you create the first cell, you then set the tags of the checkinBtn to 0. After you scroll that cell off-screen and it gets reused, you will no longer be able to find the button at the index 9 or 10 since you previously changed that tag.

What you should do instead doing tag-magic is create a a custom subclass of UITableViewCell where you create outlets for all the needed interface elements and access them via the outlets instead of the tags. After you create the subclass, assign it in the storyboard to the cell.

Upvotes: 1

Related Questions