UICollectionView Horizontal Scrollling Delay loading cells - ios

Trying to add a horizontal Scrolling UICollectionView of times. The problem is after a bunch of cells, it's like the next ones are loading late. I have to frequently scroll all the way over the screen until the next group of cell will load. In the screen shot, the times 2:30PM & 3:00PM should already be visible.
View Controller
GHTMeetingTimesCollectionViewFlowLayout *timesFlowLayout = [[GHTMeetingTimesCollectionViewFlowLayout alloc] init];
timesFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
timesFlowLayout.itemSize = CGSizeMake(kIconCellItemWidth, kIconCollectionHeight);
self.timesSelectCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:timesFlowLayout];
self.timesSelectCollectionView.translatesAutoresizingMaskIntoConstraints = NO;
self.timesSelectCollectionView.allowsMultipleSelection = YES;
self.timesSelectCollectionView.showsHorizontalScrollIndicator = NO;
self.timesSelectCollectionView.backgroundColor = [UIColor clearColor];
self.timesSelectCollectionView.delegate = self;
self.timesSelectCollectionView.dataSource = self;
[self.contentView addSubview:self.timesSelectCollectionView];
[self.timesSelectCollectionView registerClass:[GHTMeetingTimeCollectionViewCell class] forCellWithReuseIdentifier:kMeetingTimeCellIdentifier];
GHTMeetingTimesCollectionViewFlowLayout
#implementation GHTMeetingTimesCollectionViewFlowLayout
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray* arr = [super layoutAttributesForElementsInRect:rect];
for (UICollectionViewLayoutAttributes* atts in arr) {
if (nil == atts.representedElementKind) {
NSIndexPath* attsPath = atts.indexPath;
atts.frame = [self layoutAttributesForItemAtIndexPath:attsPath].frame;
}
}
return arr;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewLayoutAttributes* atts = [super layoutAttributesForItemAtIndexPath:indexPath];
CGRect adjustedFrame = atts.frame;
adjustedFrame.origin.x = indexPath.row*kIconCellItemWidth;
adjustedFrame.size.width = kIconCellItemWidth;
adjustedFrame.size.height = kIconCollectionHeight;
atts.frame = adjustedFrame;
return atts;
}
CollectionView Cell Class
#implementation GHTMeetingTimeCollectionViewCell
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
self.highlightColor = [UIColor lightBlue];
self.timeLabel = [[UILabel alloc] init];
self.timeLabel.layer.cornerRadius = 3;
self.timeLabel.clipsToBounds = YES;
self.timeLabel.font = [UIFont fontWithName:GFFontStandard size:14];
self.timeLabel.textColor = [UIColor lightBlue];
self.timeLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.timeLabel.textAlignment = NSTextAlignmentCenter;
self.timeLabel.backgroundColor = [UIColor clearColor];
[self.contentView addSubview:self.timeLabel];
[NSLayoutConstraint sidesOfChild:self.timeLabel toSidesOfParent:self.contentView margin:8];
[NSLayoutConstraint centerYOfChild:self.timeLabel toCenterYOfParent:self.contentView];
}
return self;
}
-(void)setTimeDisplay:(NSString *)time {
self.timeLabel.text = time;
}
- (void)setSelected:(BOOL)selected {
[super setSelected:selected];
self.timeLabel.backgroundColor = selected ? self.highlightColor : [UIColor clearColor];
self.timeLabel.textColor = selected ? [UIColor whiteColor] : self.highlightColor;
}
- (void)setHighlightColor:(UIColor *)highlightColor {
_highlightColor = highlightColor;
self.timeLabel.backgroundColor = self.isSelected ? _highlightColor : [UIColor clearColor];
self.timeLabel.textColor = self.isSelected ? [UIColor whiteColor] : _highlightColor;
}
Delegate method
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
GHTMeetingTimeCollectionViewCell *cell = [self.timesSelectCollectionView dequeueReusableCellWithReuseIdentifier:kMeetingTimeCellIdentifier forIndexPath:indexPath];
NSDate *date = [self.times objectAtIndex:indexPath.row];
[cell setTimeDisplay:[self.timeOnlyFormatter stringFromDate:date]];
if (self.existing) {
[cell setHighlightColor:[UIColor lightGrayColor]];
}
return cell;
}

Try it that way :
#interface GHTMeetingTimesCollectionViewFlowLayout ()
#property (nonatomic, strong) NSMutableDictionary *layoutInfo;
#end
#implementation GHTMeetingTimesCollectionViewFlowLayout
- (NSDictionary *)layoutInfo
{
if (!_layoutInfo)
{
_layoutInfo = [NSMutableDictionary dictionary];
}
return _layoutInfo;
}
- (void)prepareLayout
{
NSInteger sectionCount = [self.collectionView numberOfSections];
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
for (NSInteger section = 0; section < sectionCount; section++) {
NSInteger itemCount = [self.collectionView numberOfItemsInSection:section];
for (NSInteger item = 0; item < itemCount; item++) {
indexPath = [NSIndexPath indexPathForItem:item inSection:section];
UICollectionViewLayoutAttributes *atts = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
CGRect adjustedFrame = atts.frame;
adjustedFrame.origin.x = indexPath.row*kIconCellItemWidth;
adjustedFrame.size.width = kIconCellItemWidth;
adjustedFrame.size.height = kIconCollectionHeight;
atts.frame = adjustedFrame;
self.layoutInfo[indexPath] = atts;
}
}
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSMutableArray *allAttributes = [NSMutableArray arrayWithCapacity:self.layoutInfo.count];
[self.layoutInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath, UICollectionViewLayoutAttributes *attributes, BOOL *innerStop)
{
if (CGRectIntersectsRect(rect, attributes.frame)) {
[allAttributes addObject:attributes];
}
}];
return allAttributes;
}
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
return self.layoutInfo[indexPath];
}
#end
PS : I just wrote that, didn't test it. I hope it doesn't contain any error. But it any case, it's the way you should handle custom flow layouts.

Related

UICollectionViews not displaying cells when run on iPad

I have a UIViewController with three UICollectionViews in it. When I run the app on an iPhone, the app works fine, and the UICollectionViews populate as desired.
For the iPad version I want slightly different behaviour, and so I have to give the cells different sizes relative to the parent than the iPhone version. When I run it though - the two UICollectionViews with dynamically calculated dimensions do not display any cells. I assume the problem must be with with this code:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
if (IDIOM != IPAD)
{
if (collectionView == self.sourceTanksCollectionView)
{
return CGSizeMake(self.sourceTanksCollectionView.frame.size.width, self.sourceTanksCollectionView.frame.size.height * 0.95);
}
else if (collectionView == self.destinationTanksCollectionView)
{
return CGSizeMake(self.destinationTanksCollectionView.frame.size.width, self.destinationTanksCollectionView.frame.size.height* 0.95);
}
else
{
return CGSizeMake(50,60);
}
}
else
{
CGSize iPadCellSize;
if (collectionView == self.sourceTanksCollectionView)
{
iPadCellSize = CGSizeMake(self.sourceTanksCollectionView.frame.size.width, (self.sourceTanksCollectionView.frame.size.height/self.arrayOfSourceTanks.count));
}
else if (collectionView == self.destinationTanksCollectionView)
{
iPadCellSize = CGSizeMake(self.destinationTanksCollectionView.frame.size.width, (self.destinationTanksCollectionView.frame.size.height/self.arrayOfDestinationTanks.count));
}
else
{
iPadCellSize = CGSizeMake(50,60);
}
return iPadCellSize;
}
}
I have tried making sure the heights and widths of the cells are less than the UICollectionViews in question, but this doesn't make any difference.
OK - I'm still not having any luck with this! The UICollectionViews work on the iPhone5 and iPhone6 I have tested it on - it's just the iPad version. I am hoping this is still something simple. Here is the rest of the code I use for the collectionviews - maybe there is something I have not spotted:
- (void)viewDidLoad {
[super viewDidLoad];
self.lhsGradientFillView.firstColor = [UIColor lightBlue];
self.lhsGradientFillView.secondColor = [UIColor transparentLightBlue];
self.rhsGradientFillView.firstColor = [UIColor lightBlue];
self.rhsGradientFillView.secondColor = [UIColor transparentLightBlue];
self.lhsGradientFillView.gradientDirection = dLeftToRight;
self.rhsGradientFillView.gradientDirection = dRightToLeft;
self.currentSelectedMovement = 0;
self.movementsIndexCollectionView.delegate = self;
self.movementsIndexCollectionView.dataSource = self;
self.sourceTanksCollectionView.delegate = self;
self.sourceTanksCollectionView.dataSource = self;
self.destinationTanksCollectionView.delegate = self;
self.destinationTanksCollectionView.dataSource = self;
self.blendDataProvider = [[BlendDataProvider alloc] init];
self.blendDataProvider.dataDelegate = self;
[self.blendDataProvider getArrayOfBlends];
self.movementIndicatorArrow.direction = dUp;
self.transferDirectionArrow.direction = dDown;
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(didChangeOrientation:) name:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice]];
UICollectionViewFlowLayout* sourceFlowLayout = (UICollectionViewFlowLayout*)self.sourceTanksCollectionView.collectionViewLayout;
UICollectionViewFlowLayout* destinationFlowLayout = (UICollectionViewFlowLayout*)self.destinationTanksCollectionView.collectionViewLayout;
if (IDIOM==IPAD)
{
UICollectionViewFlowLayout* srcLayout = (UICollectionViewFlowLayout*)self.sourceTanksCollectionView.collectionViewLayout;
srcLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
UICollectionViewFlowLayout* destLayout = (UICollectionViewFlowLayout*)self.destinationTanksCollectionView.collectionViewLayout;
destLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
sourceFlowLayout.itemSize = CGSizeMake(self.sourceTanksCollectionView.frame.size.width, self.sourceTanksCollectionView.frame.size.height/2);
destinationFlowLayout.itemSize = CGSizeMake(self.destinationTanksCollectionView.frame.size.width, self.destinationTanksCollectionView.frame.size.height/2);
[self.sourceTanksCollectionView.collectionViewLayout invalidateLayout];
[self.destinationTanksCollectionView.collectionViewLayout invalidateLayout];
}
else
{
UICollectionViewFlowLayout* srcLayout = (UICollectionViewFlowLayout*)self.sourceTanksCollectionView.collectionViewLayout;
srcLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
UICollectionViewFlowLayout* destLayout = (UICollectionViewFlowLayout*)self.destinationTanksCollectionView.collectionViewLayout;
destLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
sourceFlowLayout.itemSize = CGSizeMake(self.sourceTanksCollectionView.frame.size.width, self.sourceTanksCollectionView.frame.size.height/2);
destinationFlowLayout.itemSize = CGSizeMake(self.destinationTanksCollectionView.frame.size.width, self.destinationTanksCollectionView.frame.size.height/2);
}
self.sourceTanksCollectionView.scrollEnabled = YES;
self.sourceTanksCollectionView.pagingEnabled = YES;
self.destinationTanksCollectionView.scrollEnabled = YES;
self.destinationTanksCollectionView.pagingEnabled = YES;
self.sourceIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
self.destinationIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
self.currentBlend = [self.arrayOfBlends objectAtIndex:0];
[self.sourceTanksCollectionView setNeedsDisplay];
[self.destinationTanksCollectionView setNeedsDisplay];
}
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
if (IDIOM!=IPAD)
{
if (self.sourceIndexPath.row < self.arrayOfSourceTanks.count)
{
[UIView animateWithDuration:0 animations: ^{[self.sourceTanksCollectionView reloadData]; }
completion:^(BOOL finished){;
[self.sourceTanksCollectionView scrollToItemAtIndexPath:self.sourceIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}];
self.sourceTanksCollectionViewPageControl.currentPage = self.sourceIndexPath.row;
}
if (self.destinationIndexPath.row < self.arrayOfDestinationTanks.count)
{
[UIView animateWithDuration:0 animations: ^{[self.destinationTanksCollectionView reloadData];}
completion:^(BOOL finished){;
[self.destinationTanksCollectionView scrollToItemAtIndexPath:self.destinationIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}];
self.destinationTanksColelctionViewPageControl.currentPage = self.destinationIndexPath.row;
}
[self.movementsIndexCollectionView setNeedsDisplay];
}
else
{
self.sourceTanksCollectionViewPageControl.currentPage = self.sourceIndexPath.row;
self.destinationTanksColelctionViewPageControl.currentPage = self.destinationIndexPath.row;
[self.movementsIndexCollectionView setNeedsDisplay];
[self.sourceTanksCollectionView reloadData];
[self.destinationTanksCollectionView reloadData];
}
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
if ([collectionView isEqual:self.movementsIndexCollectionView])
{
if ([[self.arrayOfAllMovements objectAtIndex:indexPath.row] isKindOfClass:[Movement class]])
{
TransfersListCollectionViewCell* tempCell = [collectionView dequeueReusableCellWithReuseIdentifier: #"Transfer List Cell" forIndexPath:indexPath];
Movement* thisMovement = [self.arrayOfAllMovements objectAtIndex:indexPath.item];
tempCell.sourceTankLabel.text = thisMovement.sourceTank.tankNumber;
[tempCell bringSubviewToFront:tempCell.sourceTankLabel];
tempCell.destinationTankLabel.text = thisMovement.destinationTank.tankNumber;
tempCell.tankGauge.percentFilled = [thisMovement.transferredVolume doubleValue]/[thisMovement.totalVolume doubleValue];
tempCell.tankGauge.lightFillColor = [UIColor lightestBlue];
tempCell.tankGauge.darkFillColor = [UIColor midBlue];
[tempCell sendSubviewToBack:tempCell.tankGauge];
[tempCell.tankGauge setNeedsDisplay];
[tempCell setNeedsDisplay];
return tempCell;
}
else
{
}
}
else if ([collectionView isEqual:self.sourceTanksCollectionView])
{
SourceTankCollectionViewCell* tempCell = [collectionView dequeueReusableCellWithReuseIdentifier: #"Source Tank Collection Cell" forIndexPath:indexPath];
Tank* thisSourceTank = [self.arrayOfSourceTanks objectAtIndex:indexPath.row];
Product* thisSourceTankProduct = thisSourceTank.tankProduct;
Movement* thisMovement = [self.currentBlend.movements objectAtIndex:indexPath.row];
tempCell.tankNumberLabel.text = thisSourceTank.tankNumber;
tempCell.tankProductLabel.text = thisSourceTankProduct.name;
tempCell.tankVolumeLabel.text = thisSourceTank.tankTotalVolume;
tempCell.percentageFilled = [NSNumber numberWithDouble: [thisSourceTank.tankTotalVolume doubleValue]/[thisSourceTank.tankMaxVolume doubleValue]];
tempCell.tankVolumeToTransferLabel.text = [thisMovement.totalVolume stringValue];
tempCell.tankVolumeTransferredLabel.text = [thisMovement.transferredVolume stringValue];
tempCell.transferStatusLabel.text = thisMovement.status;
if ([thisMovement.status isEqualToString:#"In Progress"])
{
tempCell.transferStatusLabel.layer.masksToBounds = YES;
tempCell.transferStatusLabel.layer.cornerRadius = 8;
tempCell.transferStatusLabel.backgroundColor = [UIColor darkBlue];
tempCell.transferStatusLabel.textColor = [UIColor lightBlue];
}
else
{
tempCell.transferStatusLabel.layer.masksToBounds = NO;
tempCell.transferStatusLabel.layer.cornerRadius = 0;
tempCell.transferStatusLabel.backgroundColor = [UIColor lightBlue];
tempCell.transferStatusLabel.textColor = [UIColor darkBlue];
}
tempCell.backgroundColor = [UIColor lightBlue];
tempCell.layer.borderWidth = 1.5;
tempCell.layer.borderColor = [[UIColor darkBlue] CGColor];
tempCell.layer.cornerRadius = 8;
[tempCell setNeedsDisplay];
return tempCell;
}
else if ([collectionView isEqual:self.destinationTanksCollectionView])
{
DestinationTankCollectionViewCell* tempCell = [collectionView dequeueReusableCellWithReuseIdentifier: #"Destination Tank Collection Cell" forIndexPath:indexPath];
Tank* thisDestinationTank = [self.arrayOfDestinationTanks objectAtIndex:indexPath.item];
Product* thisDestinationTankProduct = thisDestinationTank.tankProduct;
tempCell.tankNumberLabel.text = thisDestinationTank.tankNumber;
tempCell.tankProductLabel.text = thisDestinationTankProduct.name;
tempCell.tankVolumeLabel.text = thisDestinationTank.tankTotalVolume;
tempCell.percentageFilled = [NSNumber numberWithDouble:[thisDestinationTank.tankTotalVolume doubleValue]/[thisDestinationTank.tankMaxVolume doubleValue]];
tempCell.backgroundColor = [UIColor lightBlue];
tempCell.layer.borderWidth = 1.5;
tempCell.layer.borderColor = [[UIColor darkBlue] CGColor];
tempCell.layer.cornerRadius = 8;
[tempCell setNeedsDisplay];
return tempCell;
}
return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
if (IDIOM != IPAD)
{
if (collectionView == self.sourceTanksCollectionView)
{
return CGSizeMake(self.sourceTanksCollectionView.frame.size.width, self.sourceTanksCollectionView.frame.size.height * 0.95);
}
else if (collectionView == self.destinationTanksCollectionView)
{
return CGSizeMake(self.destinationTanksCollectionView.frame.size.width, self.destinationTanksCollectionView.frame.size.height* 0.95);
}
else
{
return CGSizeMake(50,60);
}
}
else
{
CGSize iPadCellSize;
if (collectionView == self.sourceTanksCollectionView)
{
//iPadCellSize = CGSizeMake(self.sourceTanksCollectionView.frame.size.width/4, (self.sourceTanksCollectionView.frame.size.height/self.arrayOfSourceTanks.count)/4);
iPadCellSize = CGSizeMake(0, 0);
}
else if (collectionView == self.destinationTanksCollectionView)
{
//iPadCellSize = CGSizeMake(self.destinationTanksCollectionView.frame.size.width/4, (self.destinationTanksCollectionView.frame.size.height/self.arrayOfDestinationTanks.count)/4);
iPadCellSize = CGSizeMake(0, 0);
}
else
{
iPadCellSize = CGSizeMake(50,60);
}
return iPadCellSize;
}
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
double xInset;
UIEdgeInsets inset;
if ([collectionView isEqual:self.movementsIndexCollectionView])
{
xInset = (self.movementsIndexCollectionView.frame.size.width/2) - 25;
inset = UIEdgeInsetsMake(0, xInset, 0, xInset);
}
return inset;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//we need to make sure that the cell that has been selected has a transfer associated with it!
if (collectionView == self.movementsIndexCollectionView && [[collectionView cellForItemAtIndexPath:indexPath] isKindOfClass:[TransfersListCollectionViewCell class]])
{
NSIndexPath* previousCurrentMovement = [NSIndexPath indexPathForItem:self.currentSelectedMovement inSection:0];
self.currentSelectedMovement = indexPath.row;
self.currentMovement = [self.arrayOfAllMovements objectAtIndex:indexPath.row];
Movement* thisMovement = [self.arrayOfAllMovements objectAtIndex:indexPath.row];
for (Blend* thisBlend in self.arrayOfBlends)
{
if (thisBlend.dbId == thisMovement.blendId)
{
self.currentBlend = thisBlend;
[self loadSourceTanksInToArray];
[self loadDestinationTanksInToArray];
for (int i=0; i<self.arrayOfSourceTanks.count; i++)
{
Tank* srcTank = [self.arrayOfSourceTanks objectAtIndex:i];
if ([thisMovement.sourceTank isEqual:srcTank])
{
self.sourceIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
}
}
for (int i=0; i<self.arrayOfDestinationTanks.count; i++)
{
Tank* destTank = [self.arrayOfDestinationTanks objectAtIndex:i];
if ([thisMovement.destinationTank isEqual:destTank])
{
self.destinationIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
}
}
}
}
[self.movementsIndexCollectionView deselectItemAtIndexPath:previousCurrentMovement animated:NO];
[self.movementsIndexCollectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
[self.movementsIndexCollectionView setNeedsDisplay];
[self viewDidLayoutSubviews];
}
}

UITableview load default selected values with checkmark in ios

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;

CollectionView memory VM:CoreAnimation memory allocated and abandoned

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

UILabel showing wrong

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.

label display text not well when use [cell setNeedsDisplay]

I have a UICollectionView to display username of user, and when I add new or modify a user -> I will update into database -> then get all data again(from the data base). and then reload UICollectionView. All I want is: if I modify a user at index 3 then after reload this user is still stay at index 3(and if I add a new user this user will display at the end position). So that I use setNeedsDisplay. But I have a problem that my label display text not well when I use setNeedsDisplay,as below:
when I comment out [cell setNeedsDisplay]; then the text of label is display well. But the index of each user is not display right as I want.Here is my code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
if(!dbManager)
dbManager = [DBManager sharedInstant];
UIBarButtonItem *btnAdd = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showAdd)];
self.navigationItem.rightBarButtonItem = btnAdd;
UIBarButtonItem *btnFilter = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:#selector(showFilter)];
self.navigationItem.leftBarButtonItem = btnFilter;
[[DBManager sharedInstant] setDelegate:self];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView setBackgroundColor:[UIColor clearColor]];
[self.collectionView registerClass:[UserCollectionItemView class] forCellWithReuseIdentifier:#"UserCollectionItemView"];
cells = [[NSMutableArray alloc] init];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if (!dbManager.synchronized) {
[datasource removeAllObjects];
datasource = nil;
if (contactType == ContactTypeCustomer)
[dbManager requestData:kDbCustomers predicate:nil target:self];
else if (contactType == ContactTypeSuppplier)
[dbManager requestData:kDbSuppliers predicate:nil target:self];
}
[self setLayout];
}
and for collectionview:
#pragma mark
#pragma UICollectionDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)cv numberOfItemsInSection:(NSInteger)section
{
return [datasource count];
}
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
[cells addObject:cell];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UserCollectionItemView *cell;
// if([cells count])
// {
// cell = [cells lastObject];
// [cells removeLastObject];
// }
// else
cell = [cv dequeueReusableCellWithReuseIdentifier:#"UserCollectionItemView" forIndexPath:indexPath];
if (contactType == ContactTypeCustomer) {
POSCustomer *customer = [datasource objectAtIndex:indexPath.item];
cell.displayname = customer.CompanyName;
}
else if (contactType == ContactTypeSuppplier){
POSSupplier *supplier = [datasource objectAtIndex:indexPath.item];
cell.displayname = supplier.CompanyName;
}
cell.backgroundColor = [UIColor clearColor];
[cell setNeedsDisplay];
return cell;
}
- (void)collectionView:(UICollectionView *)cv didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
dbManager.synchronized = YES;
if (contactType == ContactTypeCustomer) {
POSCustomer *customers = [datasource objectAtIndex:indexPath.item];
[self showEditCustomer:customers];
}
else if (contactType == ContactTypeSuppplier){
POSSupplier *suppliers = [datasource objectAtIndex:indexPath.item];
[self showEditSupplier:suppliers];
}
}
-(void)showEditCustomer:(POSCustomer *)customer{
ContactFormViewController *form = [[ContactFormViewController alloc] initWithNibName:#"ContactFormViewController" bundle:nil];
[form setContactType:ContactTypeCustomer];
form.posCustomer = customer;
[self.navigationController pushViewController:form animated:YES];
}
-(void)showEditSupplier:(POSSupplier *)supplier{
ContactFormViewController *form = [[ContactFormViewController alloc] initWithNibName:#"ContactFormViewController" bundle:nil];
[form setContactType:ContactTypeSuppplier];
form.posSupplier = supplier;
[self.navigationController pushViewController:form animated:YES];
}
#pragma mark
#pragma DBDelegate
- (void)requestDataCompleted:(NSMutableArray *)results
{
datasource = results;
[self.collectionView reloadData];
}
and here is for custom collectionview:
#synthesize displayname;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect
{
CGRect frame = self.contentView.frame;
UIView *view = [[UIView alloc] initWithFrame:frame];
view.layer.borderWidth = 0.5;
[view.layer setBorderColor:[UIColor colorWithRed:0.3 green:0.6 blue:0.2 alpha:1].CGColor];
view.layer.cornerRadius = 5;
[view setBackgroundColor:[UIColor colorWithRed:0.3 green:0.6 blue:0.2 alpha:0.3]];
UIImageView *avatarView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, frame.size.width, rect.size.width)];
[avatarView setBackgroundColor:[UIColor clearColor]];
[avatarView setImage:[UIImage imageNamed:#"users_icon"]];
[view addSubview:avatarView];
UILabel *displayName = [[UILabel alloc] initWithFrame:CGRectMake(3, frame.size.width - 10, rect.size.width - 6, 50)];
displayName.numberOfLines = 2;
displayName.text = displayname;
[displayName setFont:[UIFont fontWithName:#"Arial" size:12]];
displayName.textAlignment = NSTextAlignmentCenter;
[displayName setTextColor:[UIColor colorWithRed:0.3 green:0.6 blue:0.2 alpha:1]];
[view addSubview:displayName];
[self.contentView addSubview:view];
}
Thanks for any helps.
Because of this line [self.contentView addSubview:view];, It've added multiple times because setNeedDisplay will call drawRect: every time. To avoid this, try below..
UIView *view = [[UIView alloc] initWithFrame:frame];
view.tag = SomeTagValue;
.
.
.
.
UIView *preView = [self.contentView viewWithTag:SomeTagValue];
[preView removeFromSuperview];
[self.contentView addSubview:view];

Resources