UISegmentedControl changes tableView datasource.
After I described [myView addSubview:_tableView];
instead of [self.view addSubview:_tableView];,
daySegmentedControl process stopped working.
I have this code.
ViewController.m
#implementation ViewController
{
int _tableType;
NSArray *_data1;
NSArray *_data2;
}
#synthesize segment;
#synthesize daySegment;
#synthesize myView;
- (void)viewDidLoad
{
[super viewDidLoad];
_tableType = 1;
_data1 = #[#[#"A",#"B",#"C"]];
_data2 = #[#[#"D",#"E",#"F"]];
myView = [[UIView alloc]initWithFrame:CGRectMake(-1, 44, 340, 480)];
[self.view addSubview:myView];
myView.opaque = NO;
myView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.0f];
[self.view bringSubviewToFront:myView];
[self segmentView];
[self daySegmentView];
[self dayTableView];
}
- (void)segmentView
{
NSArray *SegmentContent = [NSArray arrayWithObjects:#"View1",#"View2",nil];
segment = [[UISegmentedControl alloc] initWithItems:WDSegmentContent];
segment.frame = CGRectMake(-2, 20, 326, 25);
segment.selectedSegmentIndex = 0;
[segment addTarget:self action:#selector(WDSegmentAction:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:segment];
}
- (void)WDSegmentAction:(id)sender
{
switch (segment.selectedSegmentIndex){
case 0:
[self dayTableView];
break;
case 1:
[self dayTableView];
break;
default:
break;
}
}
- (void)daySegmentView
{
NSArray *daySegmentContent = [NSArray arrayWithObjects:#"A",#"D",nil];
daySegment = [[UISegmentedControl alloc] initWithItems:daySegmentContent];
daySegment.frame = CGRectMake(0, 0, 326, 25);
daySegment.selectedSegmentIndex = 0;
[daySegment addTarget:self action:#selector(daySegmentAction:) forControlEvents:UIControlEventValueChanged];
[myView addSubview:daySegment];
}
- (void)daySegmentAction:(id)sender
{
switch (segment.selectedSegmentIndex){
case 0:
_tableType = 1;
[self.tableView reloadData];
break;
case 1:
_tableType = 2;
[self.tableView reloadData];
break;
default:
break;
}
}
- (void)dayTableView
{
_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 30, 320, 480)];
_tableView.dataSource = self;
_tableView.delegate = self;
[myView addSubview:_tableView];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_data1[section]count];
}
- (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];
}
NSString *data;
if (_tableType == 1) {
data = _data1[indexPath.section][indexPath.row];
} else if (_tableType == 2){
data = _data2[indexPath.section][indexPath.row];
}
cell.textLabel.text = data;
return cell;
}
#end
Any idea on how I could fix it?
I used different approach for changing segments. Just for illustration:
in segment changed method:
[_tableView reloadData];
In your numberOfRowsInSection:
if(_segControl.selectedSegmentIndex == 0)
{
return [dataSourceOne count];
}else
{
return [dataSourceTwo count];
}
}
In your heightForRowAtIndexPath
if(_segControl.selectedSegmentIndex == 0) { //one
return 60;
} else { //two
return 70;
}
In your cellForRowAtIndexPath
if(_segControl.selectedSegmentIndex == 0) {
//generate and populate cell for type one
}else
{
//generate and populate cell for type two
}
Use daySegment.selectedSegmentIndex instead of segment.selectedSegmentIndex in
- (void)daySegmentAction:(id)sender
Related
First of all sorry for asking this as I know there are a lot of questions which are similar to this. But so far nothing has worked for me. I have a table view with two buttons. On click of the button it loads two different custom cells. But I can't seem to clear out the old cell values no matter what I try. I have tried the prepareForReuse method to clear the old views but I end up with nothing displaying on the cells.
Here is the code that I am using.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([[self.sections objectAtIndex:indexPath.section] count] > 0)
{
id object = [[self.sections objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
if (indexPath.section == self.sections.count-1)
{
if(self.CategoryButtonType == 0)
{
MediaListCarousel * cell = [self getMediaCellCarousel:object];
return cell;
}
else
{
NonMediaTableViewCell * cell = [self getNonMediaCell:object];
return cell;
}
}
else
{
//Do other stuff
}
}
return nil;
}
Here are the custom cells
-(NonMediaTableViewCell *)getNonMediaCell:(NSString *)name
{
NonMediaTableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:nonmediaCellIdentifier];
if (cell == nil) {
cell = (NonMediaTableViewCell*)[VFHelper findCellWithClassName:[NonMediaTableViewCell class] nibName:#"NonMediaTableViewCell"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
[cell setNonMediaWithPackageName:name
delegate:self];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
-(MediaListCarousel *)getMediaCellCarousel:(NSString *)name
{
MediaListCarousel * cell = [self.tableView dequeueReusableCellWithIdentifier:mediaCellIdentifier];
if (cell == nil) {
cell = (MediaListCarousel*)[VFHelper findCellWithClassName:[MediaListCarousel class] nibName:#"MediaListCarousel"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
[cell setUp:name delegate:self];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
each of those custom cell has the prepareForReuse method as defined below.
- (void)prepareForReuse {
[super prepareForReuse];
// Clear contentView
BOOL hasContentView = [self.subviews containsObject:self.contentView];
if (hasContentView) {
for(UIView *subview in [self.contentView subviews])
{
[subview removeFromSuperview];
}
}
}
What happening when i add the removeFromSuperview in the prepareForReuse method I can empty view when I switch between the two views. If i dont use the prepareForReuse to remove the view I end up with views on top of each other when I click the different button. Can some one please help with this. Thanks in advance.
EDIT TO SHOW CUSTOM CELL CODE
-(void) getNonMediaCell:(NSString *)package
delegate:(NSObject <nonMediaCellDelegate> *)delegate
{
self.package = package;
[self loadValuefFromDB];
self.addonName = addonName;
_delegate = delegate;
[self.btnSeemore addTarget:self action:#selector(btnSeemoreClicked) forControlEvents:UIControlEventTouchUpInside];
if(_addons.isHidden)
{
_planDescTextView.hidden = YES;
_heightConstraintforPlanDescView.constant = 0;
_btnSeemore.imageView.transform = CGAffineTransformIdentity;
}
else
{
_planDescTextView.text = description;
CGSize neededSize = [_planDescTextView sizeThatFits:CGSizeMake(_planDescTextView.frame.size.width, CGFLOAT_MAX)];
_planDescTextView.hidden = NO;
_heightConstraintforPlanDescView.constant = neededSize.height + 5;
_btnSeemore.imageView.transform = CGAffineTransformMakeRotation(M_PI);
_btnSeemore.imageView.clipsToBounds = NO;
_btnSeemore.imageView.contentMode = UIViewContentModeCenter;
}
if(IsEmpty(addons.state))
{
_UIViewEntitlement.hidden = YES;
_UIViewBtnRepurchase.hidden = YES;
_seperatorView.hidden = YES;
[self resetCell];
[self setPriceLabelValue];
[self.purchaseBtn addTarget:self action:#selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
self.purchaseBtn.accessibilityLabel = [NSString stringWithFormat:#"%#_Purcahse", addonName];
self.purchaseBtn.accessibilityValue = [NSString stringWithFormat:#"%#_Purcahse", addonName];
self.purchaseBtn.accessibilityIdentifier = [NSString stringWithFormat:#"%#_Purcahse", addonName];
self.recurringIndicatorImageView.hidden = NO;
[self addOnRecurringIndicatorImages];
}
else
{
_UIViewEntitlement.hidden = NO;
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 20)];
VFAddonPlanentitlementCell * cell = (VFAddonPlanentitlementCell*)[VFHelper findCellWithClassName:[VFAddonPlanentitlementCell class] nibName:#"VFAddonPlanentitlementCell"];
[cell setFrame:CGRectMake(0, 0, self.frame.size.width, 20)];
if(!IsEmpty(_addons.remainingDays))
{
if(recurring || allowCancel)
{
if([[_addons.state uppercaseString] isEqualToString:#"ONHOLD"])
{
[cell setDaysRemainingColorWithTitleOnHold:#"Renews" daysRemainings:[_addons.remainingDays stringValue]];
}
else
{
[cell setRemainingColorWithTitle:#"Renews" daysRemainings:[_addons.remainingDays stringValue]];
}
}
else
{
[cell setDaysRemainingColorWithTitle:#"Time left" daysRemainings:[_addons.remainingDays stringValue]];
}
[headerView addSubview:cell];
}
[_UIViewEntitlement addSubview:headerView];
}
}
try this
-(void) getNonMediaCell:(NSString *)package
delegate:(NSObject <nonMediaCellDelegate> *)delegate
{
.....//other code
UIView *headerView = [_UIViewEntitlement viewWithTag:12345];
if(headerView == nil) {
headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 20)];
[headerView setTag:12345];//set tag
} else {
NSLog(#"headerView already exist");
}
//set values
.....//other code
}
and in reuse method
- (void)prepareForReuse {
[super prepareForReuse];
UIView *header = [_UIViewEntitlement viewWithTag:12345];//use same tag
[header removeFromSuperview];
}
if you are creating and adding multiple views programatically, then set tag to each views and remove those in reuse by accessing it with same tag value.
I have a method setting up value for table view for multi-selection row
- (id)initWithTitle:(NSString *)aTitle options:(NSArray *)aOptions matchingArray:(NSArray *)matchArray xy:(CGPoint)point size:(CGSize)size isMultiple:(BOOL)isMultiple
{
isMultipleSelection=isMultiple;
float height = MIN(size.height, DROPDOWNVIEW_HEADER_HEIGHT+[aOptions count]*44);
CGRect rect = CGRectMake(point.x, point.y, size.width, height);
if (self = [super initWithFrame:rect])
{
self.backgroundColor = [UIColor clearColor];
self.layer.shadowColor = [UIColor blackColor].CGColor;
self.layer.shadowOffset = CGSizeMake(2.5, 2.5);
self.layer.shadowRadius = 2.0f;
self.layer.shadowOpacity = 0.5f;
_kTitleText = [aTitle copy];
_kDropDownOption = #[#"India",#"Swaziland",#"Africa",#"Australlia",#"Pakistan",#"Srilanka",#"Mexico",#"United Kingdom",#"United States",#"Portugal"];
_kMatchingArray = #[#"United States",#"Swaziland"];
finalarray=[[NSMutableArray alloc]init];
for(int i = 0;i<[_kMatchingArray count];i++)
{
for(int j= 0;j<[_kDropDownOption count];j++)
{
if([[_kMatchingArray objectAtIndex:i] isEqualToString:[_kDropDownOption objectAtIndex:j]])
{
NSLog(#"%d",j);
NSString *str = [NSString stringWithFormat:#"%d",j];
[finalarray addObject:str];
}
else {
}
}
}
NSLog(#"finalArray:%#",finalarray);
// NSLog(#"%#",_kMatchingArray);
self.arryData=[[NSMutableArray alloc]init];
_kTableView = [[UITableView alloc] initWithFrame:CGRectMake(DROPDOWNVIEW_SCREENINSET,
DROPDOWNVIEW_SCREENINSET + DROPDOWNVIEW_HEADER_HEIGHT,
rect.size.width - 2 * DROPDOWNVIEW_SCREENINSET,
rect.size.height - 2 * DROPDOWNVIEW_SCREENINSET - DROPDOWNVIEW_HEADER_HEIGHT - RADIUS)];
_kTableView.separatorColor = [UIColor colorWithWhite:1 alpha:.2];
_kTableView.separatorInset = UIEdgeInsetsZero;
_kTableView.backgroundColor = [UIColor clearColor];
_kTableView.dataSource = self;
_kTableView.delegate = self;
[self addSubview:_kTableView];
if (isMultipleSelection) {
UIButton *btnDone=[UIButton buttonWithType:UIButtonTypeCustom];
[btnDone setFrame:CGRectMake(rect.origin.x+182,rect.origin.y-45, 82, 31)];
[btnDone setImage:[UIImage imageNamed:#"done#2x.png"] forState:UIControlStateNormal];
[btnDone addTarget:self action:#selector(Click_Done) forControlEvents: UIControlEventTouchUpInside];
[self addSubview:btnDone];
}
}
return self;
}
using this i have create a tableview fetching the values
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_kDropDownOption count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cel lForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentity = #"DropDownViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentity];
cell = [[DropDownViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity];
NSInteger row = [indexPath row];
// NSIndexPath *selectedIndexPath = [finalarray addObject:indexPath.row];
UIImageView *imgarrow=[[UIImageView alloc]init ];
NSLog(#"aray:%#",self.arryData);
if([self.arryData containsObject:indexPath]){
imgarrow.frame=CGRectMake(230,2, 27, 27);
imgarrow.image=[UIImage imageNamed:#"check_mark#2x.png"];
} else
imgarrow.image=nil;
[cell addSubview:imgarrow];
cell.textLabel.text = [_kDropDownOption objectAtIndex:row] ;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if (isMultipleSelection) {
if([self.arryData containsObject:indexPath]){
[self.arryData removeObject:indexPath];
} else {
[self.arryData addObject:indexPath];
}
[tableView reloadData];
} else {
if (self.delegate && [self.delegate respondsToSelector:#selector(DropDownListView:didSelectedIndex:)]) {
[self.delegate DropDownListView:self didSelectedIndex:[indexPath row]];
}
// dismiss self
[self fadeOut];
}
}
I have two array one have total records of the tableview and another one have initially selected values.I have compare the two arrays and get matching indexpath. My problem was how to set check mark image on matched values row?
if ([_strProIDNS isEqualToString:strUNAssignNS])
{
tblViewCell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
tblViewCell.accessoryType = UITableViewCellAccessoryNone;
I am having two table views (table, table2) in scroll view. I want to scroll the table view left to right and right to left. in this below code 1st table view (table) appears, but when I swipe right to left 2nd table view (table2) is not appearing there. blank screen appears there. please help me in coding.
- (void)viewDidLoad
{
[super viewDidLoad];
UIScrollview * theScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
theScrollView.contentSize = CGSizeMake(320*2, self.theScrollView.frame.size.height);
theScrollView.delegate = self;
theScrollView.bounces = YES;
theScrollView.showsVerticalScrollIndicator = YES;
theScrollView.showsHorizontalScrollIndicator = YES;
[self.view addSubview:theScrollView];
UITableView * table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
table.contentSize=CGSizeMake(320,200);
[table setDataSource:self];
[table setDataSource:self];
[table setDelegate:self];
[table setTranslatesAutoresizingMaskIntoConstraints: YES];
table.tag = 100;
[theScrollView addSubview:self.table];
UITableView * table2 = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
table2.contentSize=CGSizeMake(320,200);
[table2 setDataSource:self];
[table2 setDelegate:self];
table2.tag = 101;
[theScrollView addSubview:self.table2];
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.theScrollView = nil;
self.table = nil;
self.table2 = nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (tableView.tag == 100) {
return 3;
}
if (tableView.tag == 101) {
return 4;
}
return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView.tag == 100) {
return 5;
}
if (tableView.tag == 101) {
return 5;
}
return 0;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (tableView.tag == 100) {
return [NSString stringWithFormat:#"%#", #"Plain"];
}
if (tableView.tag == 101) {
return [NSString stringWithFormat:#"%#", #"Group"];
}
return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView.tag == 100) {
static NSString *cellIdentifier1 = #"cellIdentifier1";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier1];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier1] ;
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
cell.textLabel.text = #"45";
return cell;
}
if (tableView.tag == 101) {
static NSString *cellIdentifier2 = #"cellIdentifier2";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier2];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier2] ;
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.text = #"45";;
return cell;
}
return nil;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
float x = scrollView.contentOffset.x;
if (x > 320/2 && x < 640/2) {
self.title = #"TableView Group";
}
if (x > 0 && x < 320/2) {
self.title = #"TableView Plain";
[self.table reloadData];
}
}
According to your code, you setting equal frame for both table views:
CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
So by adding them to scroll view, you just placing them on top of each other.
Try to change the frame for second table view:
CGRectMake(320, 0, self.view.frame.size.width, self.view.frame.size.height)
I have a some collectionViews and one table view that are in the same view controller. The rather strange problem is that when i scroll up-down I alway get memory increases.
Instruments show a lot of allocation of VM:CoreAnimation objects but I can't track them down (they are inside collectionView itself).
prepare for reuse is getting called inside the cells, I checked this.
Here is the code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.receivedChannels = NO;
self.ItemsDict = [NSMutableDictionary new];
self.crtBatchSet = [NSMutableIndexSet new];
if ([[PSDeviceInfo sharedInstance] is_iPad]) {
self.epgWidth = EPG_WIDTH_IPAD;
} else {
self.epgWidth = EPG_WIDTH_IPHONE;
}
crtBatchSetSize = 0;
self.currentSelecteIndexOfDateCell = 0;
//size
self.widthDictionary = [NSMutableDictionary new];
self.centerXDictionary = [NSMutableDictionary new];
self.layout = [[MultipleLineLayout alloc] initWithWidthDictionary:self.widthDictionary andCenterXDictionary:self.centerXDictionary];
self.ItemsCollectionVIew.collectionViewLayout = self.layout;
self.ItemsCollectionVIew.showsHorizontalScrollIndicator = NO;
self.ItemsCollectionVIew.showsVerticalScrollIndicator = NO;
self.layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
[self.ItemsCollectionVIew registerClass:[ItemColectionCell class] forCellWithReuseIdentifier:#"ItemColectionCellID"];
[self.hoursCollectionView registerClass:[HoursCollectionViewCell class] forCellWithReuseIdentifier:#"HoursColectionCellID"];
[self.datePickerCollectionView registerClass:[DatePickerCollectionViewCell class] forCellWithReuseIdentifier:#"DatePickerColectionCellID"];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
if (scrollView == self.ItemsCollectionVIew){
self.channelsTableView.contentOffset = CGPointMake(0, self.ItemsCollectionVIew.contentOffset.y);
self.hoursCollectionView.contentOffset = CGPointMake(self.ItemsCollectionVIew.contentOffset.x, 0);
}
if (scrollView == self.channelsTableView) {
self.ItemsCollectionVIew.contentOffset = CGPointMake(self.ItemsCollectionVIew.contentOffset.x,self.channelsTableView.contentOffset.y);
}
if (scrollView == self.hoursCollectionView) {
self.ItemsCollectionVIew.contentOffset = CGPointMake(self.hoursCollectionView.contentOffset.x,self.ItemsCollectionVIew.contentOffset.y);
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *channelCellID = #"ChannelTableCellID";
ChannelTableCell *cell = [tableView dequeueReusableCellWithIdentifier:channelCellID forIndexPath:indexPath];
cell.myIndexInTable = indexPath.row;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[cell getData];
return cell;
}
#pragma mark - UITableViewDelegate Methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self.ItemsCollectionVIew reloadData];
}
#pragma mark - UICollectionViewDataSource Methods
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
if (collectionView == self.datePickerCollectionView || collectionView == self.hoursCollectionView) {
return 1;
}else{
if (self.receivedChannels) {
return totalNoChannels;
} else {
return 1;
}
}
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
if (collectionView == self.datePickerCollectionView) {
return DELTA_DAYS + 1;
}else if (collectionView == self.hoursCollectionView) {
return 48; //24 hours * 2
}else{
// if (collectionView == self.ItemsCollectionVIew){
NSArray *sectionItems = self.ItemsDict[#(section)];
if (sectionItems) {
// return sectionItems.count;
return 100;
} else {
return 100;
}
}
return 1;
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
if (collectionView == self.datePickerCollectionView) {
static NSString *ItemCellID = #"DatePickerColectionCellID";
DatePickerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ItemCellID forIndexPath:indexPath];
[self setDayAndDateforCell:cell at:indexPath];
[cell setBackgroundColor:[self getColorForCell:self.currentSelecteIndexOfDateCell == indexPath.row ? YES:NO]];
return cell;
}else if (collectionView == self.hoursCollectionView){
static NSString *ItemCellID = #"HoursColectionCellID";
HoursCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ItemCellID forIndexPath:indexPath];
cell.hourLabel.text = [self getTimeLineCellValuerFor:indexPath];
return cell;
} else{
// if (collectionView == self.datePickerCollectionView) {
static NSString *ItemCellID = #"ItemColectionCellID";
ItemColectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ItemCellID forIndexPath:indexPath];
NSArray *Items = self.ItemsDict[#(indexPath.section)];
if (indexPath.row >= Items.count) {
return cell;
}
MvpItem *prog = Items[indexPath.row];
[cell updateInfo:prog];
[cell setBackgroundColor:[self getColorForCell:NO]];
return cell;
}
}
#pragma mark - UICollectionViewDelegate Methods
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
if (collectionView == self.datePickerCollectionView) {
self.currentSelecteIndexOfDateCell = indexPath.row;
}
if (collectionView == self.ItemsCollectionVIew) {
[self pushDetailsatIndexPath:indexPath];
}
}
The code for the tableView cell is:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
[self.layer setBorderColor:[UIColor blackColor].CGColor];
[self.layer setBorderWidth:1.0f];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)prepareForReuse{
self.thumbnailImage.image = nil;
self.channel = nil;
[self clearDelegate];
[super prepareForReuse];
}
- (void)dealloc
{
[self clearDelegate];
}
- (void)clearDelegate
{
NSString *url = self.channel.media_content.thumbPoster.url;
// [[ImageManager sharedInstance] removeDelegate:self forImgUrl:url];
[[TVManager sharedInstance] removeDelegate:self];
}
- (void)getData
{
[[TVManager sharedInstance] getChannelAndItemssForIndex:self.myIndexInTable forDateDelta:0 forDelegate:self];
}
- (void)didReceiveTotalNoChn:(NSInteger)totalChnNo{
return;
}
- (void)didReceiveChannel:(MvpChannel *)channel withItemss:(NSArray *)Itemss forDateDelta:(NSInteger)date withIndex:(NSUInteger)index{
if (index != self.myIndexInTable) {
return;
}
if ([self.channel isEqual:channel]) {
return;
}
self.channel = channel;
NSString *imgUrl = self.channel.media_content.thumbPoster.url;
// UIImage *img = [[ImageManager sharedInstance] getImageForUrl:imgUrl forIndex:self.myIndexInTable withDelegate:self];
// if (img) {
// self.thumbnailImage.image = img;
// }
}
#pragma mark - Image Delegate
- (void)didReceiveImage:(UIImage *)image forIndex:(NSInteger)index
{
if (index != self.myIndexInTable) {
return;
}
if (image) {
self.thumbnailImage.contentMode = UIViewContentModeScaleAspectFit;
self.thumbnailImage.image = image;
[self setNeedsLayout];
}
}
And inside the collectionViewCell:
#interface ItemColectionCell ()
#property (retain, nonatomic) UILabel *titleLabel;
#property (retain, nonatomic) UILabel *genreLabel;
#property (retain, nonatomic) UILabel *intervalLabel;
#end
#implementation ItemColectionCell //collection
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self.layer setBorderColor:[UIColor blackColor].CGColor];
[self.layer setBorderWidth:1.0f];
self.titleLabel = [[UILabel alloc] init];
self.genreLabel = [[UILabel alloc] init];
self.intervalLabel = [[UILabel alloc] init];
[self.titleLabel setBackgroundColor:[UIColor clearColor]];
[self.genreLabel setBackgroundColor:[UIColor clearColor]];
[self.intervalLabel setBackgroundColor:[UIColor clearColor]];
[self.titleLabel setTextColor:[UIColor whiteColor]];
[self.genreLabel setTextColor:[UIColor whiteColor]];
[self.intervalLabel setTextColor:[UIColor whiteColor]];
[self.titleLabel setFont:[UIFont fontWithName:#“cf-Bold" size:15]];;
[self.genreLabel setFont:[UIFont fontWithName:#“cf-Regular" size:11]];;
[self.intervalLabel setFont:[UIFont fontWithName:#“cf-Regular" size:11]];;
}
return self;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
- (void)prepareForReuse{
self.titleLabel.text = nil;
self.genreLabel.text = nil;
self.intervalLabel.text = nil;
[self.titleLabel removeFromSuperview];
[self.genreLabel removeFromSuperview];
[self.intervalLabel removeFromSuperview];
[super prepareForReuse];
}
- (void)updateInfo:(MvpItem*)item{
if (!item) {
return;
}
NSDateFormatter *startTimeFormat = [[NSDateFormatter alloc] init];
[startTimeFormat setDateFormat:#"hh:mm"];
NSDateFormatter *endTimeFormat = [[NSDateFormatter alloc] init];
[endTimeFormat setDateFormat:#"hh:mm a"];
NSString *startTime = [startTimeFormat stringFromDate:item.startTime];
NSString *endTime = [endTimeFormat stringFromDate:item.endTime];
self.titleLabel.frame = CGRectMake(10, 7, self.frame.size.width - 10, 15);
self.genreLabel.frame = CGRectMake(10, 20, self.frame.size.width - 10, 15);
self.intervalLabel.frame = CGRectMake(10, 32, self.frame.size.width - 10, 15);
self.titleLabel.text = item.title;
self.genreLabel.text = #“tewst”;
self.intervalLabel.text = [NSString stringWithFormat:#"%# - %#", startTime, endTime];
[self addSubview:self.titleLabel];
[self addSubview:self.genreLabel];
[self addSubview:self.intervalLabel];
}
What ca I do to solve this problem?
Did you try to remove the cell or heavy tasks triggered by displaying that cell when it did end displaying?
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
or
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
i'm using a tableview to load datas from my college db, the table load the tablecell normally... but when i scroll down the table the name of the discipline goes well but the grade is showing up one on top of above
why is that?
#import "NFMainViewController.h"
#import "NFData.h"
#interface NFMainViewController ()
#end
#implementation NFMainViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
data = [[NFData getData] objectForKey:#"data"];
cursoData = nil;
cursosView = [[UIViewController alloc] init];
[cursosView setTitle:#"Cursos"];
cursosTable = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds];
[cursosTable setDelegate:self];
[cursosTable setDataSource:self];
[cursosView.view addSubview:cursosTable];
[self pushViewController:cursosView animated:NO];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - TableView delegates
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (tableView == cursosTable) {
return [data count];
} else {
return [cursoData count];
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
static NSString *ident = #"headerIdent";
UITableViewHeaderFooterView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:ident];
if (view == nil) {
view = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:ident];
}
if (tableView == cursosTable) {
view.textLabel.text = [[data objectAtIndex:section] objectForKey:#"unidade"];
} else {
NSDictionary *temp = [cursoData objectAtIndex:section];
view.textLabel.text = [NSString stringWithFormat:#"%#º/%#", [temp objectForKey:#"semestre"], [temp objectForKey:#"ano"]];
}
return view;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == cursosTable) {
return [[[data objectAtIndex:section] objectForKey:#"cursos"] count];
} else {
return [[[cursoData objectAtIndex:section] objectForKey:#"disciplinas"] count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ident = #"cellIdent";
UITableViewCell *view = [tableView dequeueReusableCellWithIdentifier:ident];
if (view == nil) {
view = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ident];
}
if (tableView == cursosTable) {
view.textLabel.text = [[[[data objectAtIndex:indexPath.section] objectForKey:#"cursos"] objectAtIndex:indexPath.row] objectForKey:#"curso"];
} else {
UIFont *font = [UIFont fontWithName:#"Arial" size:10.0f];
view.textLabel.font = font;
view.selectionStyle = UITableViewCellSelectionStyleNone;
NSDictionary *temp = [[[cursoData objectAtIndex:indexPath.section] objectForKey:#"disciplinas"] objectAtIndex:indexPath.row];
view.textLabel.text = [temp objectForKey:#"disciplina"];
CGRect notaRect = view.bounds;
notaRect.origin.x = notaRect.size.width - 70.0f;
notaRect.size.width = 50.0f;
UILabel *nota = [[UILabel alloc] initWithFrame:notaRect];
nota.textAlignment = NSTextAlignmentRight;
nota.font = font;
nota.text = [temp objectForKey:#"nota"];
[view addSubview:nota];
CGRect labelRect = view.textLabel.frame;
labelRect.size.height -= 60;
view.textLabel.frame = labelRect;
CGRect progRect = view.bounds;
progRect.origin.x += 6.0f;
progRect.size.width -= 12.0f;
progRect.origin.y += progRect.size.height - 6.0f;
progRect.size.height = 5.0f;
UIProgressView *prog = [[UIProgressView alloc] initWithFrame:progRect];
int faltas = [[temp objectForKey:#"faltas"] intValue];
int maximo = [[temp objectForKey:#"maximo"] intValue];
float value = 1.0f * faltas / maximo;
if (value > 1.0f) {
prog.progressTintColor = [UIColor blackColor];
} else if (value == 1.0f) {
prog.progressTintColor = [UIColor redColor];
} else if (value >= 0.7f) {
prog.progressTintColor = [UIColor yellowColor];
}
[prog setProgress:value];
[view addSubview:prog];
}
return view;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == cursosTable) {
cursoData = [[[[data objectAtIndex:indexPath.section] objectForKey:#"cursos"] objectAtIndex:indexPath.row] objectForKey:#"epocas"];
notasView = [[UIViewController alloc] init];
[notasView setTitle:#"Disciplinas"];
notasTable = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds];
[notasTable setDelegate:self];
[notasTable setDataSource:self];
[notasView.view addSubview:notasTable];
[self pushViewController:notasView animated:YES];
}
}
#end
Your nota UILabel is created each time a UITableViewCell is dequeued. So the first time the tableview loads everything is fine. Then when you start scrolling, your code reuse cells with the nota label already created, but you add another label on top of it. You need to reuse the label previously created.
The best way is to create a UITableViewCell subclass with a nota property for instance.