Adding UIView to UICollectionviewcell - iphone

I have a question about adding UIView in UIcollectionviewcell. I haveUIcollectionview and is the condition, if condition is true I need to add UIView to UIcollectionviewcell. If the condition is false don't add.
After updating UIcollectionview UIView is added to Cell for which conditions is true and some for which the condition is false. How to add a UIView to UIcollectionviewcell? one, two or three UIView can be added cell.
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger dayStart = [self dayWeekStart:[self getCurentDate:indexPath.section]];
CalendarCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
if (indexPath.item+1 < dayStart) {
CalendarEmptyCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"cellemptyIdentifier" forIndexPath:indexPath];
return cell;
} else {
CalendarCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
cell.titleLabel.text = [NSString stringWithFormat:#"%i",indexPath.item-dayStart+2];
int todayDayRowInt = todayDayRow;
int dayPlusShift = todayDayRowInt + dayStart - 2;
cell.titleLabel.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:15];
CALayer* layer = [cell layer];
[layer setCornerRadius:15];
dateFormatter.dateFormat = #"yyyy-MM-dd hh:mm:ss Z";
cell.titleLabel.textColor = [UIColor lightGrayColor];
dateFromString1 = [NSDate date];
dateFromString2 = [dateFormatter dateFromString:_dateFinish];
dateFromString3 = [dateFormatter dateFromString:_dateStart];
if ([self checkDateFromCalendar:indexPath.section row:indexPath.item + 3 - dayStart] == 1) {
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[arrColor removeAllObjects];
for (int i=0; i<appDelegate.selectPill.count; i++) {
Pill *arrPill = [appDelegate.selectPill objectAtIndex:i];
NSNumber *mDay = arrPill.manyday;
int mDayInt = [mDay integerValue]+1;
if ([[self sameDateByAddingMonths:[dateFormatter dateFromString:_dateStart] addMonths:indexPath.section addDay:indexPath.item + 3 - dayStart] compare:[self sameDateByAddingMonths:arrPill.start addMonths:0 addDay:mDayInt]] == NSOrderedAscending) {
NSDate *verifiableDate = [self sameDateByAddingMonths:[dateFormatter dateFromString:_dateStart] addMonths:indexPath.section addDay:indexPath.item];
NSDate *verifiableDate2 = [self sameDateByAddingMonths:[dateFormatter dateFromString:_dateStart] addMonths:indexPath.section addDay:indexPath.item+1];
NSTimeInterval diff = [verifiableDate timeIntervalSinceDate:arrPill.start];
NSTimeInterval diff2 = [verifiableDate2 timeIntervalSinceDate:arrPill.start];
yui = (diff2 - diff);
NSInteger sss = diff / yui;
if (diff >= 0) {
float fff = fmod (sss , ([arrPill.frequency doubleValue]+1));
if (fff == 0) {
NSArray *components = [arrPill.color componentsSeparatedByString:#","];
CGFloat r = [[components objectAtIndex:0] floatValue];
CGFloat g = [[components objectAtIndex:1] floatValue];
CGFloat b = [[components objectAtIndex:2] floatValue];
CGFloat a = [[components objectAtIndex:3] floatValue];
UIColor *color = [UIColor colorWithRed:r green:g blue:b alpha:a];
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0+(i*10), (i*10), 10, 10)];
view.backgroundColor = [UIColor color];
[cell.contentView addSubview:view];
}
}
}
}
cell.titleLabel.textColor = [UIColor darkGrayColor];
} else {
cell.titleLabel.textColor = [UIColor lightGrayColor];
}
if ([dateFromString1 compare:dateFromString2] != NSOrderedDescending && [dateFromString1 compare:dateFromString3] != NSOrderedAscending) {
if (indexPath.section == todayMonthSection && indexPath.item == dayPlusShift){
cell.backgroundColor = [UIColor colorWithRed:60.0/255.0 green:162.0/255.0 blue:161.0/255.0 alpha:1];
cell.titleLabel.textColor = [UIColor whiteColor];
cell.titleLabel.font = [UIFont fontWithName:#"HelveticaNeue-Light" size:15];
} else {
cell.backgroundColor = [UIColor whiteColor];
}
}
return cell;
}
return cell;
}

Add your view visually to your
StoryBoard or Xib file and make custom cell classes make a connections
Use below code snippet
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
PhotosCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
UIView *anotherView = [[UIView alloc]initWithFrame:CGRectMake(0.0, 0.0, 20.0, 20.0)];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0.0, 0.0, 50.0, 20.0)];
label.text = #"Hello";
[anotherView addSubview:label];
[cell.myView addSubview:anotherView];
if("Your condition is true")
{
cell.myView.hidden = YES;
}
else
{
cell.myView.hidden = YES;
}
return cell;
}

Use the cell.contentView to get access to the cell's UIView.
Example:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = #"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
MyRootView *view = [[MyRootView alloc]initWithFrame:CGRectMake(0, 0, 100, 100) someBusinessLogicParam:1];
[cell.contentView addSubview:view];
return cell;
}
I think would help is you have a root view which takes in your business logic as parameters. The business parameters will determine which views to display during the root view's initWithFrame.
Modified Example of MyRootView:
- (id)initWithFrame:(CGRect)frame someBusinessLogicParam:(NSInteger)bp
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.backgroundColor = [UIColor whiteColor];
if (bp == 0) {
UIView *yourChild1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[self addSubview:yourChild1];
} else if (bp == 1) {
UIView *yourChild2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[self addSubview:yourChild2];
}else if (bp == 3) {
UIView *yourChild3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[self addSubview:yourChild3];
UIView *yourChild4 = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 50, 50)];
[self addSubview:yourChild4];
}
}
return self;
}
You can then use the cell.contentView to add in the MyRootView along with your logic to what gets displayed.

Related

How to write in the background view (Instructions mainly) of UITableView

I want to achieve something like this
mainly for Instruction purpose, is there a UITableView method I am unaware of, or there is some sort of trick.
This is written in Header and Footer of UItableView. So customize headerView and footerView of sections in table.
Use these methods :
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
Hope it helps you.
If you want to make same kind of view (as per above shown image),put a label in the footer of the section,make the background of the label transparent and set its frame according to your choice and add the text which you want to put over there. let me give you a code snippet which might help you.
UILabel *tableFooter = [[UILabel alloc] initWithFrame:footerRect];
tableFooter.textColor = // add color of your choice
tableFooter.backgroundColor = // add color of your choice
tableFooter.opaque = YES;
tableFooter.font = [UIFont boldSystemFontOfSize:15];
tableFooter.text = #" add text of your choice";
self.theTable.tableFooterView = tableFooter;
[tableFooter release];
Put the above code in this method :
- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
Check out this delegate method:
- (NSString *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
You following methods its works for me in my app :
- (void)viewDidLoad {
[super viewDidLoad];
/* ios 7 Change */
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
{
self.edgesForExtendedLayout = UIRectEdgeNone;
self.edgesForExtendedLayout = UIRectEdgeNone;
self.tableview.separatorInset = UIEdgeInsetsZero;
[self.tableview setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
NSString *header;
float start = 10.0, startLabel = 10.0;
if ([UICommonUtils isiPad])
{
startLabel = 50.0;
} else {
startLabel = 10.0;
}
CGRect rectFrame = [UIScreen mainScreen].applicationFrame;
UIView* customView = [[[UIView alloc]
initWithFrame:CGRectMake(start, 0.0, rectFrame.size.width - 20.0, 80.0)]
autorelease];
/*
customView.backgroundColor =
[UIColor colorWithRed:.6 green:.6 blue:1 alpha:.9];
*/
UILabel * headerLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
//UILabel * headerLabel = [[[UILabel alloc] initWithStyle:UITableViewCellStyleDefault] autorelease];
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.opaque = NO;
//headerLabel.textColor = [UIColor darkGrayColor];
headerLabel.textColor = [UIColor colorWithRed:0.298039 green:0.337255 blue:0.423529 alpha:1];
headerLabel.shadowColor = [UIColor whiteColor];
headerLabel.shadowOffset = CGSizeMake(0.0, 1.0);
headerLabel.font = [UIFont boldSystemFontOfSize:17.0];
//headerLabel.frame = CGRectMake(startLabel, 0, rectFrame.size.width - 60.0, 20.0);
headerLabel.frame = CGRectMake(startLabel, 10, rectFrame.size.width - 35.0, 20.0);
headerLabel.textAlignment = UITextAlignmentLeft;
headerLabel.lineBreakMode = UILineBreakModeWordWrap;
headerLabel.text = header;
headerLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
UILabel * footerLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
//UILabel *footerLabel = [[[UILabel alloc] initWithStyle:UITableViewCellStyleDefault] autorelease];
footerLabel.backgroundColor = [UIColor clearColor];
footerLabel.opaque = NO;
//footerLabel.textColor = [UIColor darkGrayColor];
footerLabel.textColor = [UIColor colorWithRed:0.298039 green:0.337255 blue:0.423529 alpha:1];
footerLabel.shadowColor = [UIColor whiteColor];
footerLabel.shadowOffset = CGSizeMake(0.0, 1.0);
footerLabel.font = [UIFont systemFontOfSize:14.0];
float height;
if ([UICommonUtils isiPad])
height = 40.0;
else
height = 50.0;
footerLabel.frame = CGRectMake(startLabel, 20, rectFrame.size.width - 60.0, height);
footerLabel.textAlignment = UITextAlignmentLeft;
footerLabel.lineBreakMode = UILineBreakModeWordWrap;
footerLabel.baselineAdjustment = UIBaselineAdjustmentNone;
footerLabel.numberOfLines = 0;
footerLabel.text = detail;
[customView addSubview:headerLabel];
[customView addSubview:footerLabel];
return customView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
if ([UICommonUtils isiPad]) return 60.0;
else return 70.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 0;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section
{
return kProductHeader;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
/* ios 7 Change */
if ([cell respondsToSelector:#selector(tintColor)]) {
if (tableView == self.tableview) {
CGFloat cornerRadius = 5.f;
cell.backgroundColor = UIColor.clearColor;
CAShapeLayer *layer = [[CAShapeLayer alloc] init];
CGMutablePathRef pathRef = CGPathCreateMutable();
CGRect bounds = CGRectInset(cell.bounds, 10, 0);
BOOL addLine = NO;
if (indexPath.row == 0 && indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
} else if (indexPath.row == 0) {
CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
addLine = YES;
} else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
} else {
CGPathAddRect(pathRef, nil, bounds);
addLine = YES;
}
layer.path = pathRef;
CFRelease(pathRef);
layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;
if (addLine == YES) {
CALayer *lineLayer = [[CALayer alloc] init];
CGFloat lineHeight = (1.f / [UIScreen mainScreen].scale);
lineLayer.frame = CGRectMake(CGRectGetMinX(bounds)+10, bounds.size.height-lineHeight, bounds.size.width-10, lineHeight);
lineLayer.backgroundColor = tableView.separatorColor.CGColor;
[layer addSublayer:lineLayer];
}
UIView *testView = [[UIView alloc] initWithFrame:bounds];
[testView.layer insertSublayer:layer atIndex:0];
testView.backgroundColor = UIColor.clearColor;
cell.backgroundView = testView;
}
}
}

The first UITableViewCell's accessary arrow is not showing

Here is the code I am struggling with, the first table cell doesnt display the accessary arrow, but other table cells work fine...
Below is the code for table cell1, other cells is also customized but work fine.
- (void) initialization
{
labelTitle = [[UILabel alloc] initWithFrame:CGRectZero];
labelTitle.font = [UIFont fontForMoreLikeResultTitle];
labelTitle.textColor = [UIColor blackColor];
labelTitle.numberOfLines = 1;
labelTitle.lineBreakMode = UILineBreakModeTailTruncation;
labelTitle.backgroundColor = [UIColor clearColor];
labelFulLAddress = [[UILabel alloc] initWithFrame:CGRectZero];
labelFulLAddress.font = [UIFont fontForMoreLikeResultDescription];
labelFulLAddress.textColor = [UIColor blackColor];
labelFulLAddress.numberOfLines = 1;
labelFulLAddress.lineBreakMode = UILineBreakModeTailTruncation;
labelFulLAddress.backgroundColor = [UIColor clearColor];
[[self contentView] addSubview:labelTitle];
[[self contentView] addSubview:labelFulLAddress];
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self)
{
// Initialization code
[self initialization];
}
return self;
}
- (void) layoutSubviews
{
float xOffset = 20.0f;
float yOffset = 10.0f;
float currentUsedHeight = yOffset;
labelTitle.text = documentTitle;
labelTitle.frame = CGRectMake(xOffset, currentUsedHeight,
320.0f - 2 * xOffset, 60.0f);
[labelTitle sizeToFitHeight];
[labelTitle sizeToFitWidth];
labelFulLAddress.text = #"99999 Bellevue Way NE, Bellevue WA";
currentUsedHeight += (yOffset + labelTitle.frame.size.height);
labelFulLAddress.frame = CGRectMake(xOffset, currentUsedHeight, 320.0f - 2 * xOffset, 60.0f);
[labelFulLAddress sizeToFitHeight];
[labelFulLAddress sizeToFitWidth];
}
Below is the code in view controller:
- (UITableViewCell *) createResultTableCell1:(UITableView *)tableView
{
static NSString *CellIdentifier = #"FirstMoreLikeResultCell";
FirstResultTableCell *cell = (FristResultTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[MoreLikeTableCell1 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.documentTitle = self.documentTitle;
return cell;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
if (indexPath.row == 0)
{
cell = [self createResultTableCell1:tableView];
}
else
{
cell = [self createResultTableCell2:tableView cellForRowAtIndexPath:indexPath];
}
return cell;
}
Call [super layoutSubviews] from within your overridden layoutSubviews.

Having trouble with cells repeating

I have the following method that loads cells into my table. The cell with text "No Results" is being repeated though as I scroll. What am I doing wrong with the dequeueing?
- (UITableViewCell *)tableView:(UITableView *)iTableView cellForRowAtIndexPath:(NSIndexPath *)iIndexPath {
static NSString *kCellID = #"cellID";
UITableViewCell *aCell = [iTableView dequeueReusableCellWithIdentifier:kCellID];
if (aCell == nil) {
aCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellID] autorelease];
}
if (iTableView == self.searchDisplayController.searchResultsTableView) {
if (self.isSearching) {
static NSString *aProgressIdentifier = #"SearchProgress";
aCell = [iTableView dequeueReusableCellWithIdentifier:aProgressIdentifier];
if (!aCell) {
aCell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:aProgressIdentifier] autorelease];
}
aCell.userInteractionEnabled = NO;
UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectZero];
aLabel.text = #"Searching...";
aLabel.font = [UIFont systemFontOfSize:16.0f];
aLabel.textColor = [UIColor grayColor];
aLabel.textAlignment = UITextAlignmentCenter;
[aLabel sizeToFit];
aLabel.frame = CGRectMake(floorf((self.view.frame.size.width / 2.0f) - (aLabel.frame.size.width / 2.0f)), floorf((aCell.frame.size.height / 2.0f) - (aLabel.frame.size.height / 2.0f)), aLabel.frame.size.width, aLabel.frame.size.height);
[aCell addSubview:aLabel];
[aLabel release];
UIActivityIndicatorView *aSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[aCell addSubview:aSpinner];
aSpinner.frame = CGRectMake(floorf((aCell.frame.size.width / 2.0f) - (aSpinner.frame.size.width / 2.0f)) - floorf(aLabel.frame.size.width / 2.0f) - 20.0f, floorf((aCell.frame.size.height / 2.0f) - (aSpinner.frame.size.height / 2.0f)), aSpinner.frame.size.width, aSpinner.frame.size.height);
[aSpinner startAnimating];
[aSpinner release];
} else {
Class anObject = [self.masterArray objectAtIndex:iIndexPath.section];
if ([anObject isKindOfClass: [NSArray class]]) {
NSArray *sectionArray = [self.masterArray objectAtIndex:iIndexPath.section];
if (sectionArray.count > 0) {
id aCellObject = [sectionArray objectAtIndex:iIndexPath.row];
if ([aCellObject isKindOfClass:[CMACustomer class]]) {
CMACustomer *aCustomerObject = aCellObject;
aCell.textLabel.
text = aCustomerObject.customerFullName;
aCell.detailTextLabel.text = nil;
} else if ([aCellObject isKindOfClass:[CMAReservation class]]) {
CMAReservation *aReservationObject = aCellObject;
aCell.textLabel.text = aReservationObject.fullName;
aCell.detailTextLabel.text = aReservationObject.orderDescription;
// aCell.detailTextLabel.text = aReservationObject.reservationTimeAndDate;
}
} else {
aCell.userInteractionEnabled = NO;
UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectZero];
aLabel.text = #"No Results.";
aLabel.font = [UIFont systemFontOfSize:16.0f];
aLabel.textColor = [UIColor grayColor];
aLabel.textAlignment = UITextAlignmentCenter;
[aLabel sizeToFit];
aLabel.frame = CGRectMake(floorf((self.view.frame.size.width / 2.0f) - (aLabel.frame.size.width / 2.0f)), floorf((aCell.frame.size.height / 2.0f) - (aLabel.frame.size.height / 2.0f)), aLabel.frame.size.width, aLabel.frame.size.height);
[aCell addSubview:aLabel];
[aLabel release];
}
}
}
} else {
NSString *aLocalizedTitle = [[self.defaultScopeArray objectAtIndex:iIndexPath.row] objectForKey:#"localizedTitle"];
NSString *aDefaultTitle = [[self.defaultScopeArray objectAtIndex:iIndexPath.row] objectForKey:#"defaultTitle"];
aCell.textLabel.text = CMALocalizedStringWithDefaultValue(aLocalizedTitle, aDefaultTitle);
if ([[[self.currentScopeArray objectAtIndex:iIndexPath.row] objectForKey:#"enabledByDefault"] boolValue]) {
aCell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
aCell.accessoryType = UITableViewCellAccessoryNone;
}
}
return aCell;
}
A couple of things:
If you just want text labels in your cells there is no need to add a UILabel to the tableViewCell. Just use the textLabel property of the cell or the detailTextLabel property (depending on the tableviewcell type you're using).
If you do want to add a UILabel you should add it to the contentView property of the tableViewCell.
When you are adding views to a tableViewcell, you really shouldn't alloc/init it outside of the if(!Cell) {} block as every time you're recycling that tableViewcell, another another UILabel is alloc/init'd.
According to the code you posted and the problem you are seeing, it looks like sectionArrayis empty. Where is that being filled?

UITableView with performance issues

I make an UITableview (with IB) in my application with 3 types of cell. All works fine except when i drag my tableview all become very slow. So if someone can help me to improve the performance of my app it'll be cool.
My Code for the tableview :
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[myData objectForKey:#"listnews"] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) {
return 154;
}
if (indexPath.row == 1) {
return 34;
}
else return 70;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[myTextField resignFirstResponder];
ListNewsCell *cCell = (ListNewsCell *)[myTable dequeueReusableCellWithIdentifier:[NSString stringWithFormat:#"cCellIdentifier%d",indexPath.row]];
cCell = [[ListNewsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:#"cCellIdentifier%d",indexPath.row]];
if (indexPath.row == 0) {
NSString * caroline = [[[myData objectForKey:#"listnews"] objectAtIndex:indexPath.row] objectForKey:#"urlimage"];
cCell.c1Image1.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",caroline]]]];
cCell.c1Image2.image = [UIImage imageNamed:#"barreNoireHub.png"];
NSString * sophie = [[[myData objectForKey:#"listnews"] objectAtIndex:indexPath.row] objectForKey:#"titre"];
NSString *itemTitle = sophie ? [sophie stringByConvertingHTMLToPlainText] : #"[No Title]";
cCell.c1Label1.text = itemTitle;
NSString * sonia = [[[myData objectForKey:#"listnews"] objectAtIndex:indexPath.row] objectForKey:#"extrait"];
NSString *itemExtrait = sonia ? [sonia stringByConvertingHTMLToPlainText] : #"[No Title]";
cCell.c1Label2.text = itemExtrait;
}
if (indexPath.row == 1) {
UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 34)];
imageView.backgroundColor = [UIColor whiteColor];
imageView.image = [UIImage imageNamed:#"barreSearchHub.png"];
[cCell addSubview:imageView];
[imageView release];
UIView * insertView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 34)];
myTextField = [[UITextField alloc] initWithFrame:CGRectMake(15, 6, 270, 25)];
myTextField.placeholder = #"Recherche";
myTextField.tag = 1;
myTextField.delegate = self;
myTextField.returnKeyType = UIReturnKeySearch;
[insertView addSubview:myTextField];
cCell.accessoryView = insertView;
}
if (indexPath.row > 1) {
cCell.c2Image1.image = [UIImage imageNamed:#"cellM.png"];
NSString * caroline = [[[myData objectForKey:#"listnews"] objectAtIndex:indexPath.row] objectForKey:#"urlimage"];
cCell.c2Image2.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",caroline]]]];
NSString * sophie = [[[myData objectForKey:#"listnews"] objectAtIndex:indexPath.row] objectForKey:#"titre"];
NSString *itemTitle = sophie ? [sophie stringByConvertingHTMLToPlainText] : #"[No Title]";
cCell.c2Label1.text = itemTitle;
NSString * sonia = [[[myData objectForKey:#"listnews"] objectAtIndex:indexPath.row] objectForKey:#"extrait"];
NSString *itemExtrait = sonia ? [sonia stringByConvertingHTMLToPlainText] : #"[No Title]";
cCell.c2Label2.text = itemExtrait;
}
return cCell;
}
The code of the UITableViewCell:
#import "ListNewsCell.h"
#implementation ListNewsCell
#synthesize c1Image1, c1Image2, c1Label1, c1Label2;
#synthesize c2Image1, c2Image2, c2Label1, c2Label2;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
c1Image1 = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,154)];
c1Image1.backgroundColor = [UIColor clearColor];
[self addSubview:c1Image1];
[c1Image1 release];
c1Image2 = [[UIImageView alloc] initWithFrame:CGRectMake(0,98,320,56)];
c1Image2.backgroundColor = [UIColor clearColor];
[self addSubview:c1Image2];
[c1Image2 release];
c1Label1 = [[UILabel alloc] initWithFrame:CGRectMake(5, 100, 310, 20)];
c1Label1.font = [UIFont fontWithName:#"Arial-BoldMT" size:14];
c1Label1.textColor = [UIColor whiteColor];
c1Label1.backgroundColor = [UIColor clearColor];
[self addSubview:c1Label1];
c1Label2 = [[UILabel alloc] initWithFrame:CGRectMake(5, 112, 310, 45)];
c1Label2.font = [UIFont fontWithName:#"Arial" size:12];
c1Label2.textColor = [UIColor whiteColor];
c1Label2.numberOfLines = 2;
c1Label2.backgroundColor = [UIColor clearColor];
[self addSubview:c1Label2];
c2Image1 = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,70)];
c2Image1.backgroundColor = [UIColor clearColor];
[self addSubview:c2Image1];
[c2Image1 release];
c2Label1 = [[UILabel alloc] initWithFrame:CGRectMake(105, 8, 180, 20)];
c2Label1.font = [UIFont fontWithName:#"Arial-BoldMT" size:14];
c2Label1.textColor = [UIColor blackColor];
c2Label1.backgroundColor = [UIColor clearColor];
[self addSubview:c2Label1];
c2Label2 = [[UILabel alloc] initWithFrame:CGRectMake(105, 25, 180, 45)];
c2Label2.font = [UIFont fontWithName:#"Arial" size:12];
c2Label2.textColor = [UIColor blackColor];
c2Label2.numberOfLines = 2;
c2Label2.backgroundColor = [UIColor clearColor];
[self addSubview:c2Label2];
c2Image2 = [[UIImageView alloc] initWithFrame:CGRectMake(20,10,75,55)];
c2Image2.backgroundColor = [UIColor clearColor];
[self addSubview:c2Image2];
[c2Image2 release];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
}
- (void)dealloc
{
[super dealloc];
}
#end
Thanks to all !
The following line causes the big delay:
cCell.c2Image2.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",caroline]]]];
Everytime one of these cells will be loaded, it will make a URL Request. Try to preload a bunch of the data instead of requesting it per cell.
Load the image once, make it a class variable, then just reuse its pointer like:
cCell.c2Image2.image = preloadedImage;
Declare in your .h file:
UIImage * preloadedImage;
And in the - (void) loadView -method put:
preloadedImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",caroline]]]];
Also mind that as jrturton wrote, you want to reuse your dequeued cells for the extra performance boost.
You are never reusing your dequeued cells, so you are recreating everything from scratch every time. Since you have a unique cell for each row (is this really necessary for cells in row 2 and above?) you only need to create and populate them once.
So, you could wrap everything after dequeueReusableCellWithIdentifier onwards inside if (cCell == nil) (the return statement excepted, obviously).
In cellForRowAtIndexPath method you have dequeued some cells from the table view. But you have never used that value. That caused the problem of loading every time rather than re-using.
Try the following code in which I've modified a little..
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[myTextField resignFirstResponder];
ListNewsCell *cCell = (ListNewsCell *)[myTable dequeueReusableCellWithIdentifier:[NSString stringWithFormat:#"cCellIdentifier%d",indexPath.row]];
if(cCell == nil)
{
cCell = [[ListNewsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[NSString stringWithFormat:#"cCellIdentifier%d",indexPath.row]];
}
if (indexPath.row == 0) {
// Some code here
}
if (indexPath.row == 1) {
//Some code here
}
if (indexPath.row > 1) {
// some code here
}
return cCell;
}
Thanks,
Arun.

Custom uitableview cell issue

I have a custom UITableViewCell as such:
#implementation CellWithThreeSubtitles
#synthesize title, subTitle1, subTitle2, subTitle3;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
self.textLabel.backgroundColor = self.backgroundColor;
self.textLabel.opaque = NO;
self.textLabel.textColor = [UIColor blackColor];
self.textLabel.highlightedTextColor = [UIColor whiteColor];
self.textLabel.font = [UIFont boldSystemFontOfSize:22.0];
}
return self;
}
- (void)layoutSubviews
{
[super layoutSubviews];
CGRect contentRect = self.contentView.bounds;
CGRect frame = CGRectMake(35.0, 0, contentRect.size.width, 50.0);
self.textLabel.frame = frame;
UILabel *subLabel1 = [[UILabel alloc] init];
frame = CGRectMake(35.0, 34.0, contentRect.size.width, 25.0);
subLabel1.font = [UIFont systemFontOfSize:18.0];
subLabel1.backgroundColor = [UIColor clearColor];
subLabel1.text = subTitle1;
subLabel1.opaque = NO;
subLabel1.frame = frame;
[self.contentView addSubview:subLabel1];
UILabel *subLabel2 = [[UILabel alloc] init];
frame = CGRectMake(35.0, 54.0, contentRect.size.width, 25.0);
subLabel2.font = [UIFont boldSystemFontOfSize:18.0];
subLabel2.backgroundColor = [UIColor clearColor];
subLabel2.text = subTitle2;
subLabel2.opaque = NO;
subLabel2.frame = frame;
[self.contentView addSubview:subLabel2];
UILabel *subLabel3 = [[UILabel alloc] init];
frame = CGRectMake(contentRect.size.width-100.0, 54.0, contentRect.size.width, 25.0);
subLabel3.font = [UIFont systemFontOfSize:18.0];
subLabel3.backgroundColor = [UIColor clearColor];
subLabel3.text = subTitle3;
subLabel3.opaque = NO;
subLabel3.frame = frame;
[self.contentView addSubview:subLabel3];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)dealloc {
[super dealloc];
[subTitle4 release];
[subTitle3 release];
[subTitle2 release];
[subTitle1 release];
[title release];
}
When I implement it in my UITableView like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
int section = [indexPath indexAtPosition:0];
static NSString *kCustomCellID = #"AppointmentCellID";
CellWithThreeSubtitles *cell = (CellWithThreeSubtitles *)[tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil) {
cell = (CellWithThreeSubtitles *)[[[CellWithThreeSubtitles alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCustomCellID] autorelease];
}
switch (section) {
case 0:
if ([wineArray count]==0) {
cell.textLabel.text = #"No wine favorites selected yet";
}else{
cell.subTitle1 = [[wineArray objectAtIndex:indexPath.row] objectForKey:#"Varietal"];
cell.subTitle2 = [NSString stringWithFormat:#"Bin No. %#", [[wineArray objectAtIndex:indexPath.row] objectForKey:#"Bin"]];
cell.subTitle3 = [NSString stringWithFormat:#"$%#", [[wineArray objectAtIndex:indexPath.row] objectForKey:#"Price"]];
cell.textLabel.text = [NSString stringWithFormat:#"%# (%#)", [[wineArray objectAtIndex:indexPath.row] objectForKey:#"Name"], [[wineArray objectAtIndex:indexPath.row] objectForKey:#"Availability"]];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.userInteractionEnabled = NO;
break;
case 1:
if ([dinnerArray count]==0)
cell.textLabel.text = #"No dinner favorites selected yet";
else
cell.textLabel.text = [NSString stringWithFormat:#"%#", [[dinnerArray objectAtIndex:indexPath.row] objectForKey:#"Name"]];
break;
}
return cell;
}
the contents of the cell duplicates on top of itself every time the orientation of the device changes. Is it redrawing the cell every time the device rotates? And if so, How can I keep it from doing so?
You should be creating the subviews and adding them to your cell's subviews array in your -initWithStyle:reuseIdentifier: method. You only need to create the subviews once. The -layoutSubviews method is invoked repeatedly by the framework whenever the device orientation changes, to allow you to resize and/or move the subviews (plus make any other minor adjustments) to compensate for differences between the orientations.
I suspect layoutSubViews is being called on rotation, and re-drawing new labels on top of your old ones. If you remove any labels from the table cell at the beginning of layoutSubViews that would probably fix that issue, or you could create them in the init and then just position them in layoutSubViews.