I'm working with UICollectionView and I have a main class and another one which is a subclass of UICollectionViewFlowLayout. The thing it's that the cell's width and height in main class it's 0. In subclass the cell have the right size.
Here's some code:
The FlowLayoutSubClass
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewLayoutAttributes* currentItemAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];
if (!currentItemAttributes) {
currentItemAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
}
CGFloat containerWidth = self.collectionView.frame.size.width;
CGFloat cellWidth = containerWidth / 2.0f - 1.0f;
CGFloat baseHeight = containerWidth / 4.0f;
CGRect frame = [self frameForIndexPath:indexPath];
if (CGRectEqualToRect(frame, CGRectZero)) {
ArtworkModel *currentObject = [self.artworksArray objectAtIndex:indexPath.row];
CGFloat height = currentObject.height;
frame.origin = [self getNextFreePosition];
frame.size.width = cellWidth;
frame.size.height = 120 + arc4random() % (200 - 120);
[self saveFrame:frame forIndexPath:indexPath];
[self saveFrame:frame];
}
currentItemAttributes.frame = frame;
currentItemAttributes.size = frame.size;
return currentItemAttributes;
}
- (CGRect)frameForIndexPath:(NSIndexPath *)indexPath {
CGRect frame = CGRectZero;
NSString *key = [NSString stringWithFormat:#"%ld-%ld", (long)indexPath.section, (long)indexPath.row];
NSString *frameString = [self.framesByIndexPath objectForKey:key];
if (frameString) {
frame = CGRectFromString(frameString);
}
return frame;
}
- (void)saveFrame:(CGRect)frame forIndexPath:(NSIndexPath *)indexPath {
if (!self.framesByIndexPath) {
self.framesByIndexPath = [[NSMutableDictionary alloc] init];
}
NSString *key = [NSString stringWithFormat:#"%d-%d", indexPath.section, indexPath.row];
[self.framesByIndexPath setObject:NSStringFromCGRect(frame) forKey:key];
}
- (CGPoint)getNextFreePosition {
CGFloat containerWidth = self.collectionView.frame.size.width;
CGFloat cellWidth = containerWidth / 2.0f;
CGPoint point = CGPointZero;
NSArray *leftFrames = [self.framesDictionary valueForKey:#"left"];
NSArray *rightFrames = [self.framesDictionary valueForKey:#"right"];
NSString *lastLeftFrameString = [leftFrames lastObject];
NSString *lastRightFrameString = [rightFrames lastObject];
if (lastLeftFrameString == nil) {
// There is no frame saved yet, so this will be the first
point.x = 0.0f;
point.y = 0.0f;
} else {
if (lastRightFrameString == nil) {
// There is no item on the right side
point.x = cellWidth;
point.y = 0.0f;
} else {
// There are items on both left and right sides...
// Check which one has the smallest Y component
CGRect leftFrame = CGRectFromString(lastLeftFrameString);
CGRect rightFrame = CGRectFromString(lastRightFrameString);
if (CGRectGetMaxY(leftFrame) <= CGRectGetMaxY(rightFrame)) {
// We put this one on the left
point.x = 0.0f;
point.y = CGRectGetMaxY(leftFrame);
} else {
point.x = cellWidth;
point.y = CGRectGetMaxY(rightFrame);
}
}
}
return point;
}
- (void)saveFrame:(CGRect)frame {
if (!self.framesDictionary) {
self.framesDictionary = [[NSMutableDictionary alloc] init];
}
NSString *sideKey = nil;
if (CGRectGetMinX(frame) == 0.0f) {
// left
sideKey = #"left";
} else {
sideKey = #"right";
}
NSMutableArray *frames = [self.framesDictionary objectForKey:sideKey];
if (!frames) {
frames = [[NSMutableArray alloc] init];
[self.framesDictionary setObject:frames forKey:sideKey];
}
[frames addObject:NSStringFromCGRect(frame)];
}
#end
and the main class:
- (void)takeAllArtworks {
[WaitingView showWaitingView:shadowView WithIndicator:indicatorActivity];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableString *requestURL = [[NSMutableString alloc] init];
[requestURL appendFormat:#"%#%#", BASE_URL_ARTWORK, GET_ARTWORKS];
// NSInteger screenWidth = self.view.frame.size.width / 2.0f;
[manager GET:requestURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
if ([[responseObject objectForKey: #"status"] integerValue] == 0) {
NSArray *artworks = [responseObject objectForKey:#"Data"];
if ([artworks count] > 0) {
for (NSDictionary *dict in artworks) {
ArtworkModel *artwork = [[ArtworkModel alloc] init];
if ([dict objectForKey:#"Title"] != [NSNull null]) {
artwork.title = [dict objectForKey:#"Title"];
}
if ([dict objectForKey:#"Description"] != [NSNull null]) {
artwork.descriptionAlbum = [dict objectForKey:#"Description"];
}
if ([dict objectForKey:#"ArtistName"] != [NSNull null]) {
artwork.artistName = [dict objectForKey:#"ArtistName"];
}
NSString *dateAdded = [[dict objectForKey:#"DateAdded"] substringWithRange:NSMakeRange(0, 19)];
NSString *dateUpdated = [[dict objectForKey:#"DateUpdated"] substringWithRange:NSMakeRange(0, 19)];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *dateAd = [formatter dateFromString:dateAdded];
NSDate *dateUp = [formatter dateFromString:dateUpdated];
NSString *result;
if ([dateAd compare:dateUp] == NSOrderedAscending) {
result = [NSString stringWithFormat:#"edited %#", [self relativeDateStringForDate:dateUp]];
} else {
result = [self relativeDateStringForDate:dateAd];
}
artwork.dateAdded = result;
if ([dict objectForKey:#"MediaItems"] != [NSNull null]) {
NSArray *mediaArray = [dict objectForKey:#"MediaItems"];
if ([mediaArray count] > 0) {
for (NSDictionary *mediaDict in mediaArray) {
// NSString *endpoint = [NSString stringWithFormat:#"%#.ashx?w=%ld&h=%d&mode=crop", [mediaDict objectForKey:#"Url"], (long)screenWidth, 170];
NSString *endpoint = [mediaDict objectForKey:#"Url"];
NSString *imageURL = [NSString stringWithFormat:#"%#%#", IMAGE_BASE_URL, endpoint];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
[artwork.imageUrls addObject:[UIImage imageWithData:data]];
}
}
}
[listOfArtworks addObject:artwork];
}
FBFlowLayout *layout = [[FBFlowLayout alloc] initWithArtworks:listOfArtworks];
[layout setMinimumInteritemSpacing:0.5f];
[layout setMinimumLineSpacing:0.5f];
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
[artworkCollectionView reloadData];
artworkCollectionView.collectionViewLayout = layout;
[WaitingView hideWaitingView:shadowView WithIndicator:indicatorActivity];
} else {
[WaitingView hideWaitingView:shadowView WithIndicator:indicatorActivity];
}
}
else
[WaitingView hideWaitingView:shadowView WithIndicator:indicatorActivity];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Faild");
[WaitingView hideWaitingView:shadowView WithIndicator:indicatorActivity];
}];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [listOfArtworks count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
FBWorkartCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"WorkartCollection" forIndexPath: indexPath];
ArtworkModel *artworkModel = (ArtworkModel *)[listOfArtworks objectAtIndex:indexPath.row];
cell.nameAlbumLabel.text = artworkModel.title;
cell.nameArtistLabel.text = artworkModel.artistName;
if ([artworkModel.imageUrls count] > 0) {
cell.coverAlbumPhoto.image = [artworkModel.imageUrls objectAtIndex:0];
}
cell.shadowView.alpha = 0.9;
cell.dateLabel.text = artworkModel.dateAdded;
CGFloat hue = ( arc4random() % 256 / 256.0 ); // 0.0 to 1.0
CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from white
CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0, away from black
UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
cell.backgroundColor = color;
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
ArtworkModel *artworkModel = (ArtworkModel *)[listOfArtworks objectAtIndex:indexPath.row];
FBWorkDetailsViewController *dvc = [[FBWorkDetailsViewController alloc] initWithArtwork:artworkModel];
FBLeftMenuViewController *left = [[FBLeftMenuViewController alloc] init];
MFSideMenuContainerViewController *container = [MFSideMenuContainerViewController
containerWithCenterViewController: dvc
leftMenuViewController: left
rightMenuViewController:nil
withHeader: YES];
[container.titleLabel setText:#"WORK DETAILS"];
[self.navigationController pushViewController: container animated: YES];
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return [collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath].size;
}
First of all if you have a subclass of UIcollectionViewLayout, why not set in in the Storyboard
Second, your
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return [collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath].size;
}
is redundant, have you tried to make an NSLog before return on [collectionViewLayout layoutAttributesForItemAtIndexPath:indexPath].size; does it return a valid size?
Related
I have an old project done by a developer some times ago.. This particular project has 3 collection views such as collectionAnnouncments, collectionNews and collectionBulletin.
The first collectionview collectionAnnouncments is loading a same cell 10 times. But other two sections loading the cell correctly one time as per the response count.
I don't have any idea up to now for this problem. I tried some solutions from the google but I couldn't sorted because of the bad UI and Code implementation by that developer.
Ex- He used one UICollectionView Inside a tableview and using UICollectionView Class for all 3 collectionview and used a general cell for all collectionviews.
declaration... in m file
__weak IBOutlet UITableView *table;
UICollectionView *collectionAnnouncments, *collectionBulletin,
*collectionNews;
Please check the following codes and provide me a better simple solution to fix this issue without any major modifications or re-implementation because I don't have time for that.
- (void)viewDidLoad {
[super viewDidLoad];
self.automaticallyAdjustsScrollViewInsets = NO;
home.title=[Utilities getLocalizedStringForKey:#"Home"];
[Utilities setNavigationController:self];
//self.label.text=NSLocalizedFailureReasonErrorKey
self.navigationItem.leftBarButtonItem = nil;
__block BOOL newsDone = NO, bulletInDone = NO, announcmentDone = NO, refreshed = NO;
collectionViewDic = [[NSMutableDictionary alloc]init];
[Utilities serverRequest:#{#"getNewsfeed":#"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {
collectionViewDic[#"news"] = response[#"response"];
NSArray *responseValues = [response[#"response"] allValues]; // An NSArray of NSArrays
NSMutableArray *dictionarys = [NSMutableArray new];
for (NSArray *dictArrays in responseValues) {
for (NSDictionary *dict in dictArrays) {
[dictionarys addObject:dict];
}
}
_newsArray = dictionarys;
NSLog(#"news%#",dictionarys);
// sorting to newest
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"nf_id" ascending:NO];
_sortednewsArray = [_newsArray sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"Sorted news Response -%#", _sortednewsArray);
//Registeriing the collectionview custom cell
// [UICollectionView registerClass:[CustomCell class] forCellWithReuseIdentifier:#"customCell"];
// [collectionAnnouncments registerClass:[CustomCell class] forCellWithReuseIdentifier:#"customCell"];
// [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:#"Cell"];
newsDone = YES;
if (newsDone && bulletInDone && announcmentDone && !refreshed) {
refreshed = YES;
[table reloadData];
}
} errorBlock:nil];
[Utilities serverRequest:#{#"getBulletin":#"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {
// NSString *bulletinID = #"wb_id";
collectionViewDic[#"bulletin"] = response[#"response"];
NSArray *responseValues = [response[#"response"] allValues]; // An NSArray of NSArrays
NSMutableArray *dictionarys = [NSMutableArray new];
for (NSArray *dictArrays in responseValues) {
for (NSDictionary *dict in dictArrays) {
[dictionarys addObject:dict];
}
}
_bulletinArray = dictionarys;
NSLog(#"bulletin%#",dictionarys);
// sorting to newest
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"wb_id" ascending:NO];
_sortedbulletinArray = [_bulletinArray sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"Sorted bulletin Response -%#", _sortedbulletinArray);
bulletInDone = YES;
if (newsDone && bulletInDone && announcmentDone && !refreshed) {
refreshed = YES;
[table reloadData];
}
} errorBlock:nil];
[Utilities serverRequest:#{#"getAnnouncement":#"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {
collectionViewDic[#"announcement"] = response[#"response"];
NSArray *responseValues = [response[#"response"] allValues]; // An NSArray of NSArrays
NSMutableArray *dictionarys = [NSMutableArray new];
for (NSArray *dictArrays in responseValues) {
for (NSDictionary *dict in dictArrays) {
[dictionarys addObject:dict];
}
}
_annArray = dictionarys;
NSLog(#"AnnouncementResponse%#",dictionarys);
NSLog(#" Ann ID%#", [dictionarys valueForKey:#"anc_id"]);
// sorting to newest
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"date_added" ascending:NO];
_sortedAnnArray = [_annArray sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"Sorted Array Response -%#", _sortedAnnArray);
NSLog(#"Sorted Ann Array-count%zd",_sortedAnnArray.count);
NSLog(#"Sorted Ann ID%#", [_sortedAnnArray valueForKey:#"anc_id"]);
announcmentDone = YES;
if (newsDone && bulletInDone && announcmentDone && !refreshed) {
refreshed = YES;
[table reloadData];
}
} errorBlock:nil];
menuView = [Utilities addMenuView:self];
}
-(void)getNewsFeed
{
collectionViewDic = [[NSMutableDictionary alloc]init];
[Utilities serverRequest:#{#"getNewsfeed":#"a6dba37437ced2c3b07469fd6c0661f3"} completionBlock:^(id response) {
if(response != nil)
{
if ([response isKindOfClass:[NSString class]]) {
// print response .
NSLog(#"MAIN RESPONSE!%#",response);
}
//on successfully response, which provided dictionary,
else if ([[response objectForKey:#"success"] boolValue] == true) {
// on true print response data.
collectionViewDic[#"news"] = response[#"response"];
NSArray *responseValues = [response[#"response"] allValues]; // An NSArray of NSArrays
NSMutableArray *dictionarys = [NSMutableArray new];
for (NSArray *dictArrays in responseValues) {
for (NSDictionary *dict in dictArrays) {
[dictionarys addObject:dict];
}
}
_newsArray = dictionarys;
NSLog(#"news%#",dictionarys);
// sorting to newest
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"nf_id" ascending:NO];
_sortednewsArray = [_newsArray sortedArrayUsingDescriptors:#[sortDescriptor]];
NSLog(#"Sorted news Response -%#", _sortednewsArray);
}
//on success response, with failure message which is false.
else if ([[response objectForKey:#"success"] boolValue] == false) {
// handle error on success is false.
}
}
} errorBlock:nil];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
#try {
NSString *key = #"";
if ([collectionView isEqual:collectionNews])
key = #"news";
else if ([collectionView isEqual:collectionAnnouncments])
key = #"announcement";
else if ([collectionView isEqual:collectionBulletin])
key = #"bulletin";
NSDictionary *mainDic = collectionViewDic[key];
NSArray *array = mainDic[ [mainDic allKeys][0] ];
return [array count];
} #catch (NSException *exception) {
return 0;
}
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
#try {
//NSString *key = #"";
if ([collectionView isEqual:collectionNews])
return _sortednewsArray.count;
else if ([collectionView isEqual:collectionAnnouncments])
return _sortedAnnArray.count;
else if ([collectionView isEqual:collectionBulletin])
return _sortedbulletinArray.count;
}
#catch (NSException *exception) {
return 0;
}
// return _sortedAnnArray.count + _sortednewsArray.count + _sortedbulletinArray.count;
// return [[collectionViewDic allKeys] count];
// return 50;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"generalCell" forIndexPath:indexPath];
// CustomCell *cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"customCell" forIndexPath:indexPath];
// cell.tag = indexPath.row;
[cell setTag:indexPath.row];
//UILabel *test = [cell.contentView viewWithTag:1];
UIImageView *image = [cell.contentView viewWithTag:1];
//UILabel *cellTitle = [cell.contentView viewWithTag:2];
//UILabel *cellHead =[cell.contentView viewWithTag:2];
if ([collectionView isEqual:collectionAnnouncments]) {
// NSDictionary *mainDic = collectionViewDic[#"announcement"];
// NSArray *array = mainDic[ [mainDic allKeys][indexPath.section] ];
NSDictionary *dic = _sortedAnnArray[indexPath.section] ;
collectionAnnouncments.delegate = self;
collectionAnnouncments.dataSource = self;
// cellHead.text =#"Announcements";
//cellTitle.text = dic[#"anc_title"];
if ([dic[#"announcement_images"] count] > 0)
[image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",ANNOUNCMENT_IMAGES_URL,dic[#"announcement_images"][0][#"wi_image"] ] ]] ;
}
else if([collectionView isEqual:collectionNews]) {
//cellHead.text =#"News";
// NSDictionary *mainDic = collectionViewDic[#"news"];
// NSArray *array = mainDic[ [mainDic allKeys][0] ];
NSDictionary *dic = _sortednewsArray[indexPath.section] ;
collectionNews.delegate = self;
collectionNews.dataSource = self;
//cellTitle.text = dic[#"nf_title"];
if ([dic[#"newsfeed_images"] count] > 0)
[image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",NEWS_IMAGES_URL,dic[#"newsfeed_images"][0][#"wi_image"] ] ]] ;
}
else if([collectionView isEqual:collectionBulletin]) {
// NSDictionary *mainDic = collectionViewDic[#"bulletin"];
// NSArray *array = mainDic[ _sortedbulletinArray[indexPath.section] ];
NSDictionary *dic = _sortedbulletinArray[indexPath.section] ;
collectionBulletin.delegate = self;
collectionBulletin.dataSource = self;
// cellTitle.text = dic[#"wb_title"];
if ([dic[#"bulletin_images"] count] > 0)
if ([dic[#"bulletin_images"][0][#"wi_type"] isEqualToString:#"video"]) {
[image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BULLETIN_IMAGES_URL,dic[#"ws_thumb"] ] ]] ;
}
else{
[image setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",BULLETIN_IMAGES_URL,dic[#"bulletin_images"][0][#"wi_image"] ] ]] ;
}
}
return cell;
}
#pragma mark UITableView Delegate, DataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 195.0f;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[collectionViewDic allKeys] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"tableCell"];
cell.tag = indexPath.row;
UICollectionView *c = [cell.contentView viewWithTag:111];
//c.scrollEnabled = NO;
UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
flow.minimumLineSpacing = flow.minimumInteritemSpacing = 0.0f;
flow.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width/1, c.bounds.size.height);
flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
// c.collectionViewLayout = flow;
UIView *header = [cell.contentView viewWithTag:1];
UIImageView *headerImage = [header viewWithTag:2];
UILabel *headerTitle = [header viewWithTag:3];
//NSLog(cell.tag);
switch (indexPath.row) {
case 0:
//NSLog(#"text");
headerImage.image = [UIImage imageNamed:#"Announcemets"];
//headerTitle.text = #"Announcments";
headerTitle.text=[Utilities getLocalizedStringForKey:#"Announcement"];
// NSLog(headerTitle.text);
collectionAnnouncments = c;
[collectionAnnouncments setCollectionViewLayout:flow];
collectionAnnouncments.delegate = self;
collectionAnnouncments.dataSource = self;
[collectionAnnouncments reloadData];
// NSLog(#"text");
break;
case 1:
headerImage.image = [UIImage imageNamed:#"News"];
headerTitle.text=[Utilities getLocalizedStringForKey:#"Business Highlight"];
collectionNews = c;
[collectionNews setCollectionViewLayout:flow];
collectionNews.delegate = self;
collectionNews.dataSource = self;
[collectionNews reloadData];
//NSLog(#"text");
break;
case 2:
headerImage.image = [UIImage imageNamed:#"Bulletin"];
headerTitle.text=[Utilities getLocalizedStringForKey:#"Bulletin Board"];
collectionBulletin = c;
[collectionBulletin setCollectionViewLayout:flow];
collectionBulletin.delegate = self;
collectionBulletin.dataSource = self;
[collectionBulletin reloadData];
//NSLog(#"text");
break;
default:
break;
}
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.destinationViewController isKindOfClass:[NewsListing class]]) {
NewsListing *c = segue.destinationViewController;
NSInteger row = ((UIButton *)sender).superview.superview.superview.tag;
if (row == 0) {
c.isAnnouncement = YES;
c.listingArray = collectionViewDic[#"announcement"];
}
else if (row == 1) {
c.isNews = YES;
c.listingArray = collectionViewDic[#"news"];
}
else if (row == 2) {
c.isBulletin = YES;
c.listingArray = collectionViewDic[#"bulletin"];
}
}
if ([segue.destinationViewController isKindOfClass:[NewsDetail class]]) {
NewsDetail *c = segue.destinationViewController;
UICollectionViewCell *cell = sender;
NSInteger row = ((UIButton *)sender).superview.superview.superview.tag;
if (row == 0) {
c.isAnnouncement = YES;
// NSDictionary *months = collectionViewDic[#"announcement"];
NSIndexPath *indexPath = [collectionAnnouncments indexPathForCell:cell];
// NSArray *month = months[[months allKeys][0] ];
NSArray *month = _sortedAnnArray;
c.detailDic = month[indexPath.section ];
}
else if (row == 1) {
c.isNews = YES;
// NSDictionary *months = collectionViewDic[#"news"];
NSIndexPath *indexPath = [collectionNews indexPathForCell:cell];
// NSArray *month = months[[months allKeys][0] ];
NSArray *month = _sortednewsArray;
c.detailDic = month[indexPath.section ];
}
else if (row == 2) {
c.isBulletin = YES;
// NSDictionary *months = collectionViewDic[#"bulletin"];
NSIndexPath *indexPath = [collectionBulletin indexPathForCell:cell];
// NSArray *month = months[[months allKeys][0] ];
NSArray *month = _sortedbulletinArray;
c.detailDic = month[indexPath.section ];
}
}
}
#end
According to some answers I found in Stackoverflow, I should use this piece of code:
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
[self.collectionView scrollToItemAtIndexPath:selectedRow atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}
but the scrolling freezes, so I have to set it up this way:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.navigationItem.title = [NSString stringWithString:barTitle];
self.automaticallyAdjustsScrollViewInsets = NO;
//Download JSON
NSError *error=nil;
NSURL *url = [NSURL URLWithString:urlToFollow];
data = [NSMutableData dataWithContentsOfURL: url options:NSDataReadingMappedIfSafe error:&error];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSArray *response = [dictionary objectForKey:#"items"];
articlesArray = [[NSArray alloc] initWithArray:response];
//sizes
CGFloat window_height = ([self window_height]-70.0);
CGFloat window_width = [self window_width];
CGRect frame = CGRectMake((window_width/2)-15.0f , window_height, 30.0f , 15.0f);
self.pageControl = [[UIPageControl alloc]initWithFrame:frame];
UICollectionViewFlowLayout *layout = (id) self.collectionView.collectionViewLayout;
layout.itemSize = self.collectionView.frame.size;
// Add a target that will be invoked when the page control is changed by tapping on it
[self.pageControl
addTarget:self
action:#selector(pageControlChanged:)
forControlEvents:UIControlEventValueChanged
];
// Set the number of pages to the number of pages in the paged interface
// and let the height flex so that it sits nicely in its frame
if (articlesArray.count >8) {
self.pageControl.numberOfPages = 10;
}else if (articlesArray.count <8){
self.pageControl.numberOfPages =[articlesArray count];
}
self.pageControl.autoresizingMask = UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.pageControl];
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.collectionView scrollToItemAtIndexPath:selectedRow atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}
#pragma mark uicollectionview
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [articlesArray count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
LOArcticlesCustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"MyCell" forIndexPath:indexPath];
[cell.imageView setImageWithURL:[NSURL URLWithString:[[articlesArray objectAtIndex:indexPath.row]objectForKey:#"photoUrl"]]placeholderImage:[UIImage imageNamed:#"simboloLakari29.png"]];
index= indexPath.row;
cell.lblMake.text = [NSString stringWithString:[[articlesArray objectAtIndex:indexPath.row]objectForKey:#"marca"]];
cell.lblMake.lineBreakMode = NSLineBreakByWordWrapping;
cell.lblModel.text = [NSString stringWithString:[[articlesArray objectAtIndex:indexPath.row]objectForKey:#"modelo"]];
cell.lblModel.lineBreakMode = NSLineBreakByWordWrapping;
cell.lblPrice.text = [NSString stringWithString:[[articlesArray objectAtIndex:indexPath.row]objectForKey:#"precio"]];
cell.lblOrder.text = [NSString stringWithFormat:#"%ld de %ld", (unsigned long)indexPath.row+1, (unsigned long)articlesArray.count];
return cell;
}
#pragma mark page control
- (void)pageControlChanged:(id)sender
{
UIPageControl *pageControl = sender;
CGFloat pageWidth = self.collectionView.frame.size.width;
CGPoint scrollTo = CGPointMake(pageWidth * pageControl.currentPage, 0);
[self.collectionView setContentOffset:scrollTo animated:YES];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
CGFloat pageWidth = self.collectionView.frame.size.width;
self.pageControl.currentPage = self.collectionView.contentOffset.x / pageWidth;
}
- (CGFloat) window_height {
return [UIScreen mainScreen].applicationFrame.size.height;
}
- (CGFloat) window_width {
return [UIScreen mainScreen].applicationFrame.size.width;
}
But the CollectionView goes from index=0 to the desired index and it's very annoying.
Any suggestion?
Im trying to make dynamic uitableviewcell height for my custome cell.
the cell is subclassed for adding some background.
this is my uitableview controller class :
#define PADDING 23.0f
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSUInteger count = [self.entries count];
return count + _rowcount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reuseIdentifier = #"PlaceholderCell2";
SubcategoryTableViewCell * sctvCell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if (sctvCell == nil) {
sctvCell= [[SubcategoryTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
}
NSUInteger nodeCount = [self.entries count];
sctvCell.contentView.translatesAutoresizingMaskIntoConstraints = NO;
UILabel *label = (UILabel *)[sctvCell.contentView viewWithTag:1];
if (nodeCount > 0)
{
NewsFetchAppRecord *appRecord = [self.entries objectAtIndex:indexPath.row];
[label setText:appRecord.title];
NSDictionary *attributes = #{NSFontAttributeName: [UIFont fontWithName:#"B MyFont" size:14.0f]};
CGRect rect = [appRecord.title boundingRectWithSize:CGSizeMake(label.frame.size.height - PADDING * 5, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGRect newFrame = label.frame;
newFrame.size.height = rect.size.height;
label.frame = newFrame;
[label sizeToFit];
UIView *whiteRoundedCornerView = (UIView *)[sctvCell.contentView viewWithTag:1000];
CGRect newFrame2 = whiteRoundedCornerView.frame;
newFrame2.size.width = 300;
newFrame2.size.height = rect.size.height + 160;
[ whiteRoundedCornerView setFrame:newFrame2];
}
if ((unsigned long)indexPath.row == [self.entries count] - 1){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),
^{
NewsFetchParseOperation *p = [[NewsFetchParseOperation alloc]init];
NewsFetchAppRecord *appRecord = [self.entries objectAtIndex:indexPath.row];
p.cat = appRecord.Category;
self.intindex = self.intindex + 1;
p.index = [NSString stringWithFormat:#"%d", (int)self.intindex];
p.lastid = appRecord.ids;
[p main];
dispatch_async(dispatch_get_main_queue(), ^(void)
{
[self.tableView beginUpdates];
NSMutableArray *indexPaths = [NSMutableArray array];
NSInteger currentCount = self.entries.count;
for (NSUInteger i = 0; i < p.appRecordList.count; i++) {
[indexPaths addObject:[NSIndexPath indexPathForRow:currentCount+i inSection:0]];
}
NSArray *temp_1 =[self.entries arrayByAddingObjectsFromArray:p.appRecordList];
self.entries = temp_1;
[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];
[self.tableView endUpdates];
});
});
}
return sctvCell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reuseIdentifier = #"PlaceholderCell2";
SubcategoryTableViewCell * sctvCell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if (sctvCell == nil) {
sctvCell= [[SubcategoryTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
}
NewsFetchAppRecord *appRecord = [self.entries objectAtIndex:indexPath.row];
UILabel *label = (UILabel *)[sctvCell.contentView viewWithTag:1];
NSDictionary *attributes = #{NSFontAttributeName: [UIFont fontWithName:#"B MyFont" size:14.0f]};
CGRect rect = [appRecord.title boundingRectWithSize:CGSizeMake(label.frame.size.height - PADDING * 5, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
return rect.size.height + PADDING * 6;
}
and my cell subclass :
- (void)awakeFromNib {
self.news_img.layer.cornerRadius = 4;
self.news_img.clipsToBounds = YES;
self.resource_icon_img.layer.cornerRadius = 4;
self.resource_icon_img.clipsToBounds = YES;
self.contentView.backgroundColor = [UIColor clearColor];
self.whiteroundcorner = [[UIView alloc] initWithFrame:CGRectMake(10,10,300,250)];
self.whiteroundcorner.backgroundColor = [UIColor whiteColor];
self.whiteroundcorner.layer.masksToBounds = NO;
self.whiteroundcorner.layer.cornerRadius = 3.0;
[self.whiteroundcorner.layer setShadowColor:[UIColor grayColor].CGColor];
self.whiteroundcorner.layer.shadowOffset = CGSizeMake(-1, 1);
self.whiteroundcorner.layer.shadowOpacity = 0.2;
self.whiteroundcorner.tag = 1000;
[self.contentView addSubview:self.whiteroundcorner];
[self.contentView sendSubviewToBack:self.whiteroundcorner];
}
im using story board for my table like this :
now problem is most of time the height calculated incorrectly.
also some time the height goes way beyond on cell and in the end of 10 cell
when i try to fetch new row the last cell apears incorrectly.
You will need to calculate the height for the cell after setting its content.
So something like this:
- (CGFloat)heightForCellAtIndexPath:(NSIndexPath *)indexPath {
static UITableViewCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
});
/* Method where you set the content of the cell */
[self configureCell: atIndexPath:indexPath];
return [self calculateHeightForConfiguredSizingCell:sizingCell];
}
- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell {
[sizingCell setNeedsDisplay];
[sizingCell layoutIfNeeded];
CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height;
}
I state that in my app I'm using Parse.com for storing and managing data.
In my tableview I have introduced two different custom cells. A is displayed if there is an image and the other hand is displayed if the image is not present.
Now everything seems to work but when I go to make the application run the Tableview crash reporting this error:
2013-11-22 15:36:34.256 UniGo![17186:70b]
Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:],/SourceCache/UIKit_Sim/UIKit-2903.23/UITableView.m:6246**
Can you explain where I'm wrong?
- (void)viewDidLoad {
[super viewDidLoad];
self.FFTableView.delegate = self;
self.FFTableView.dataSource = self;
CellaSelezionata = -1;
}
-(void)viewDidAppear:(BOOL)animated {
[self QueryForPost];
}
-(void)QueryForPost {
PFQuery *QueryForFriend=[PFQuery queryWithClassName:FF_AMICIZIE_CLASS];
[QueryForFriend whereKey:FF_AMICIZIE_A_USER equalTo:[PFUser currentUser]];
[QueryForFriend whereKey:FF_AMICIZIE_STATO equalTo:#"Confermato"];
[QueryForFriend includeKey:FF_AMICIZIE_DA_USER];
PFQuery *QueryYES = [PFQuery queryWithClassName:FF_POST_CLASS];
[QueryYES whereKey:FF_POST_FLASH_POST_BOOLEANVALUE equalTo:[NSNumber numberWithBool:YES]];
[QueryYES whereKey:FF_POST_SCELTI equalTo:[PFUser currentUser]];
PFQuery *normalPostByFriends = [PFQuery queryWithClassName: FF_POST_CLASS];
[normalPostByFriends whereKey: FF_POST_FLASH_POST_BOOLEANVALUE equalTo: [NSNumber numberWithBool: NO]];
[normalPostByFriends whereKey: FF_POST_UTENTE matchesKey:FF_AMICIZIE_DA_USER inQuery:QueryForFriend];
PFQuery *normalPostByUser = [PFQuery queryWithClassName:FF_POST_CLASS];
[normalPostByUser whereKey:FF_POST_FLASH_POST_BOOLEANVALUE equalTo: [NSNumber numberWithBool: NO]];
[normalPostByUser whereKey:FF_POST_UTENTE equalTo: [PFUser currentUser]];
PFQuery *query = [PFQuery orQueryWithSubqueries:#[QueryYES,normalPostByFriends,normalPostByUser]];
[query includeKey:FF_POST_UTENTE];
[query orderByDescending:FF_CREATEDAT];
[query findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
if (!error) {
ArrayforPost = [[NSMutableArray alloc] init];
for (PFObject *object in results) {
[ArrayforPost addObject:object];
}
[self.FFTableView reloadData];
}
}];
}
-(CGFloat)valoreAltezzaCella:(NSInteger)index {
PFObject *objectPost = [ArrayforPost objectAtIndex:index];
NSString *text = [objectPost objectForKey:#"Testo"];
CGSize MAX = CGSizeMake(230, 10000);
UIFont *FONT = [UIFont systemFontOfSize:14];
CGSize altezzaLabel = [text boundingRectWithSize:MAX options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:FONT }context:nil].size;
return altezzaLabel.height;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [ArrayforPost count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
PFObject *ObjectPost = [ArrayforPost objectAtIndex:indexPath.row];
// FIRST CUSTOM CELL
if (![ObjectPost objectForKey:FF_POST_IMMAGINE]) {
static NSString *IdentificazioneCella = #"CellPost";
FFCustomCellTimelineSocial * Cella = (FFCustomCellTimelineSocial *)[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCella];
if (Cella == nil) {
Cella = [[FFCustomCellTimelineSocial alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:IdentificazioneCella ];
}
Cella.backgroundCell.layer.cornerRadius = 2.0f;
Cella.backgroundCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
Cella.backgroundCell.layer.borderWidth = 1.0f;
Cella.backgroundCell.autoresizingMask = UIViewAutoresizingFlexibleHeight;
Cella.BackgroundText.layer.cornerRadius = 2.0f;
Cella.BackgroundText.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
Cella.BackgroundText.layer.borderWidth = 0.0f;
Cella.BackgroundText.autoresizingMask = UIViewAutoresizingFlexibleHeight;
Cella.TimeBackground.layer.cornerRadius = 2.0f;
Cella.TimeBackground.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
Cella.TimeBackground.layer.borderWidth = 1.0f;
Cella.ViewTestataCell.layer.cornerRadius = 2.0f;
Cella.ViewTestataCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
Cella.ViewTestataCell.layer.borderWidth = 1.0f;
Cella.FFImmagineUtente.layer.masksToBounds = YES;
Cella.FFImmagineUtente.layer.cornerRadius = 20.0f;
Cella.FFImmagineUtente.contentMode = UIViewContentModeScaleAspectFill;
Cella.FFTestoUtenteLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0f];
NSString *text = [ObjectPost objectForKey:FF_POST_TEXT];
Cella.FFTestoUtenteLabel.text = text;
[Cella.FFTestoUtenteLabel setLineBreakMode:NSLineBreakByTruncatingTail];
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd MMM"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
Cella.DataCorrente.text = dateString;
NSString *NomeUser = [[ObjectPost objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_NOMECOGNOME];
Cella.FFNomeUtenteLabel.text = NomeUser;
NSString *ImmagineUtente = [[ObjectPost objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_FOTOPROFILO];
Cella.FFImmagineUtente.file = (PFFile *)ImmagineUtente;
[Cella.FFImmagineUtente loadInBackground];
if (CellaSelezionata == indexPath.row) {
CGFloat AltezzaLabel = [self valoreAltezzaCella: indexPath.row];
Cella.FFTestoUtenteLabel.frame = CGRectMake(Cella.FFTestoUtenteLabel.frame.origin.x, Cella.FFTestoUtenteLabel.frame.origin.y, Cella.FFTestoUtenteLabel.frame.size.width, AltezzaLabel); }
else {
Cella.FFTestoUtenteLabel.frame = CGRectMake(Cella.FFTestoUtenteLabel.frame.origin.x, Cella.FFTestoUtenteLabel.frame.origin.y, Cella.FFTestoUtenteLabel.frame.size.width, 55);
}
PFObject *rowObject = [ArrayforPost objectAtIndex:indexPath.row];
if([[rowObject objectForKey:FF_POST_FLASH_POST_BOOLEANVALUE ] boolValue]) {
Cella.FlashPostImg.image = [UIImage imageNamed:#"FFNotificaFlash"];
}
else {
Cella.FlashPostImg.image = [UIImage imageNamed:#" "]; }
return Cella;
}
else {
// SECOND CUSTOM CELL
static NSString *IdentificazioneCellaIMG = #"CellIMG";
FFCustomCellWithImage * CellaIMG = (FFCustomCellWithImage * )[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCellaIMG];
CellaIMG = (FFCustomCellWithImage * )[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCellaIMG];
if (CellaIMG == nil) {
CellaIMG = [[FFCustomCellWithImage alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:IdentificazioneCellaIMG ];
}
NSString *FotoPostSocial = [ObjectPost objectForKey:FF_POST_IMMAGINE];
CellaIMG.FotoPost.file = (PFFile *)FotoPostSocial;
[CellaIMG.FotoPost loadInBackground];
CellaIMG.backgroundCell.layer.cornerRadius = 2.0f;
CellaIMG.backgroundCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
CellaIMG.backgroundCell.layer.borderWidth = 1.0f;
CellaIMG.backgroundCell.autoresizingMask = UIViewAutoresizingFlexibleHeight;
CellaIMG.TimeBackground.layer.cornerRadius = 2.0f;
CellaIMG.TimeBackground.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
CellaIMG.TimeBackground.layer.borderWidth = 1.0f;
CellaIMG.ViewTestataCell.layer.cornerRadius = 2.0f;
CellaIMG.ViewTestataCell.layer.borderColor = [UIColor colorWithRed:(219/255.0) green:(219/255.0) blue:(219/255.0) alpha:(1)].CGColor;
CellaIMG.ViewTestataCell.layer.borderWidth = 1.0f;
CellaIMG.FotoProfilo.layer.masksToBounds = YES;
CellaIMG.FotoProfilo.layer.cornerRadius = 20.0f;
CellaIMG.FotoProfilo.contentMode = UIViewContentModeScaleAspectFill;
CellaIMG.TestoPost.font = [UIFont fontWithName:#"Helvetica" size:14.0f];
NSString *text = [ObjectPost objectForKey:FF_POST_TEXT];
CellaIMG.TestoPost.text = text;
[CellaIMG.TestoPost setLineBreakMode:NSLineBreakByTruncatingTail];
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd MMM"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
CellaIMG.DataPost.text = dateString;
NSString *NomeUser = [[ObjectPost objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_NOMECOGNOME];
CellaIMG.NomeUtente.text = NomeUser;
NSString *ImmagineUtente = [[ObjectPost objectForKey:FF_POST_UTENTE] objectForKey:FF_USER_FOTOPROFILO];
CellaIMG.FotoProfilo.file = (PFFile *)ImmagineUtente;
[CellaIMG.FotoProfilo loadInBackground];
if (CellaSelezionata == indexPath.row) {
CGFloat AltezzaLabel = [self valoreAltezzaCella: indexPath.row];
CellaIMG.TestoPost.frame = CGRectMake(CellaIMG.TestoPost.frame.origin.x, CellaIMG.TestoPost.frame.origin.y, CellaIMG.TestoPost.frame.size.width, AltezzaLabel);
}
else {
CellaIMG.TestoPost.frame = CGRectMake(CellaIMG.TestoPost.frame.origin.x, CellaIMG.TestoPost.frame.origin.y, CellaIMG.TestoPost.frame.size.width, 75);
}
return CellaIMG;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; {
if (CellaSelezionata == indexPath.row) {
//SPAZIO INTERNO VERSO IL BASSO QUANDO APRI LA CELLA
return [self valoreAltezzaCella:indexPath.row] + 60 * 2;
}
else {
//GRANDEZZA CELLA PRIMA DI APRIRE
return 155 + 10 * 2;
}
}
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self valoreAltezzaCella:indexPath.row] > 65) {
return indexPath;
} else {
return nil;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (CellaSelezionata == indexPath.row) {
CellaSelezionata = -1;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
return;
}
if (CellaSelezionata >= 0) {
NSIndexPath *previousPath = [NSIndexPath indexPathForRow:CellaSelezionata inSection:0];
CellaSelezionata = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:previousPath] withRowAnimation:UITableViewRowAnimationFade];
}
CellaSelezionata = indexPath.row;
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
dequeueReusableCellWithIdentifier - can return you nil
You need to check that and create a cell if that happens:
FFCustomCellTimelineSocial * Cella = (FFCustomCellTimelineSocial *)[self.FFTableView dequeueReusableCellWithIdentifier:IdentificazioneCella];
if (Cella == nil) {
Cella = [[[FFCustomCellTimelineSocial alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
}
I'm trying to put two different UICollectionViewCells in one UICollectionView. It's working, but after some scrolls, I receive memory warnings and the app crashes.
Here is my code:
Create and fill the cells:
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"KatalogBAGCell";
BAGCell *cell = (BAGCell*)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
id unknown = [[self.katalogBAGs objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
BAGObject* bag = nil;
SerienObject* serie = nil;
NSString *filePath;
if ([unknown isKindOfClass:[SerienObject class]]) {
serie = (SerienObject*)unknown;
cell = nil;
cell = [[BAGCell alloc] initWithSerie:serie.serienID];
filePath = serie.completePath;
cell.bagText.text = serientext;
cell.directText.text = serie.serienName;
[cell.directText sizeToFit];
}
else {
bag = (BAGObject*)unknown;
if ( [self isEmptyCell:bag.fileName] ) {
cell.alpha = 0.0;
cell.hidden = cell.contentView.hidden = YES;
return cell;
}
else {
cell.alpha = 1.0;
cell.hidden = cell.contentView.hidden = NO;
// should be a real bag
if (self.viewMode==0) {
// regular floating mode
cell.fullscreenButton.hidden = NO;
[cell.bookmarkButton addTarget:self action:#selector(createBookMarkForThisBAG:) forControlEvents:UIControlEventTouchUpInside];
[cell.fullscreenButton addTarget:self action:#selector(pushToFullScreenView:) forControlEvents:UIControlEventTouchUpInside];
}
else if (self.viewMode==1) {
// fullscreen mode
cell.fullscreenButton.hidden = YES;
[cell.bookmarkButton addTarget:self action:#selector(createBookMarkForThisBAG:) forControlEvents:UIControlEventTouchUpInside];
}
filePath = bag.completePath;
// clear the reused cell
for (UIView *v in [cell.directOrderContainer subviews]) {
if ((UILabel*)v==cell.directText) {
continue;
}
[v removeFromSuperview];
}
if (SAMOADelegate.appIsInPresentationMode==NO) {
// generate the infos for the textInfoLine
NSString *artCols = #"a.vkpreis, a.ve, a.groesse, a.ausverkauft";
NSString *sqlStatement = [NSString stringWithFormat:#"SELECT %# FROM kataloge_bags_artikel as ba LEFT JOIN artikel as a ON a.artikel = ba.artikelnr where ba.bagid=%i order by ba.position_in_bag ASC", artCols, bag.bagID];
sqlite3_stmt *itemSQL;
NSString *lineText = #"";
int c = 0;
if(sqlite3_prepare_v2([ToolBox db], [sqlStatement UTF8String], -1, &itemSQL, NULL) == SQLITE_OK) {
while(sqlite3_step(itemSQL) == SQLITE_ROW) {
ArticleItem *item = [[ArticleItem alloc] init];
item.vkpreis = [[NSDecimalNumber alloc] initWithFloat:[self.helper calculateArticlePriceforPrice:sqlite3_column_double(itemSQL, 0)]];
item.verpackungseinheit = sqlite3_column_int(itemSQL, 1);
item.sizeInCM = [ToolBox convertFloatToString:sqlite3_column_double(itemSQL, 2)];
item.ausverkauft = [ToolBox checkNullString:(char *)sqlite3_column_text(itemSQL, 3)];
NSString *trenner = #"";
if (c!=0) {
trenner = #" ยท ";
}
if (item.ausverkauft.length!=0) {
// ausverkauft
NSString *price = [NSString stringWithFormat:#"- %#", SAMOADelegate.loggedInCustomer.waehrungsZeichen];
NSString *part = [NSString stringWithFormat:#"%#%# %#:%i %# %#", trenner, price, veText, item.verpackungseinheit, item.sizeInCM, cmText];
lineText = [lineText stringByAppendingString:part];
}
else {
// not ausverkauft
NSString *price = [ToolBox convertDecimalNumber: item.vkpreis withCurrencySymbol:SAMOADelegate.loggedInCustomer.waehrungsZeichen];
NSString *part = [NSString stringWithFormat:#"%#%# %#:%i %# %#", trenner, price, veText, item.verpackungseinheit, item.sizeInCM, cmText];
lineText = [lineText stringByAppendingString:part];
}
c++;
}
} else { [ToolBox logDatabaseError:_cmd]; } sqlite3_finalize(itemSQL);
bag.textInfoLine = lineText;
}
// check if this an article which you can order directly
if (bag.amountOfArticles==1) {
[self createDirectOrderViewForCell:cell andItem:bag];
[cell.directText setText:bag.marketingtext];
}
else {
cell.defaultContainer.hidden = NO;
cell.directOrderContainer.hidden = YES;
if (SAMOADelegate.appIsInPresentationMode==YES) {
[cell.bagText setText:bag.marketingtext];
}
else {
[cell.bagText setText:bag.textInfoLine];
}
}
if (bag.isBookMarked==YES) {
[cell.bookmarkButton setImage:[UIImage imageNamed:#"bookmark-icon-active.png"] forState:UIControlStateNormal];
}
else {
[cell.bookmarkButton setImage:[UIImage imageNamed:#"bookmark-icon-inactive.png"] forState:UIControlStateNormal];
}
if (SAMOADelegate.appIsInPresentationMode==YES) {
cell.bookmarkButton.hidden = YES;
}
// check if this bag is already in the cart
int artInCart = [ToolBox returnSQLCountForQuery:[NSString stringWithFormat:#"SELECT COUNT(*) FROM auftragsposition where auftragsnr = '%i' AND bagid = '%i' LIMIT 1", SAMOADelegate.currentOrder.belegnr, bag.bagID]];
if (artInCart) {
cell.isInCartStateView.image = [UIImage imageNamed:#"ordered-dot.png"];
}
else {
cell.isInCartStateView.image = [UIImage imageNamed:#"not-ordered-dot.png"];
}
self.lastLoadedBagIs = bag.bagID;
self.latestLoadedIndex = indexPath.row;
}
}
__weak UIActivityIndicatorView *iV = cell.loadingIndicator;
[cell.loadingIndicator startAnimating];
[cell.bagImageView setImageWithURL:[NSURL fileURLWithPath:filePath]
placeholderImage:nil
options:0
progress:^(NSUInteger receivedSize, long long expectedSize) { [iV startAnimating]; }
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { [iV stopAnimating];
}];
//rounded corners for the cell
[self roundedCornersForLayerinCell:cell.bagImageView.layer];
[cell.bagImageView.layer setShadowPath:[[UIBezierPath bezierPathWithRoundedRect:cell.frame cornerRadius:cell.layer.cornerRadius] CGPath]];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(10.0, 10.0)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = cell.bounds;
maskLayer.path = maskPath.CGPath;
// Set the newly created shape layer as the mask for the image view's layer
cell.layer.mask = maskLayer;
return cell;
}
and cell object *.m:
-(id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:#"BAG-Template-1" owner:self options:nil];
if (arrayOfViews.count < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
}
return self;
}
and secondary init cell:
-(id)initWithSerie:(int)serienID {
self = [super init];
if (self) {
if (serienID>0) {
// Initialization code
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:#"BAG-Template-2" owner:self options:nil];
if (arrayOfViews.count < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
}
else {
// Initialization code
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:#"BAG-Template-1" owner:self options:nil];
if (arrayOfViews.count < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
}
}
return self;
}
Any idea why I receive memory warnings?