iOS GCD use for a UITableView - ios

I have a pretty intensive UITableView that needs to be optimized a little. The question is, how to use grand central station to do it effectively. Each cell has a UIView with a couple labels and two images. I have subclassed the TableViewCell and the view's are being reused though it is still a little laggy when the table gets bigger. How would I go about using GCD to optimize the table? OR is there a better way around it? I am not very strong in thread management and looking for some advice.
Here is the code to my tableview:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
JointCAD *currentCall = [[xmlParser calls] objectAtIndex:indexPath.row];
self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"texture3.png"]];
TableViewCell *cell = (TableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.callTypeLabel.text = currentCall.currentCallType;
cell.locationLabel.text = currentCall.location;
cell.unitsLabel.text = currentCall.units;
cell.stationLabel.text = [#"Station: " stringByAppendingString:currentCall.station];
cell.selectedBackgroundView = cell.selectionView;
if ([currentCall.callType isEqualToString:#"F"]) {
cell.imageType = Fire;
}
else {
cell.imageType = EMS;
}
if ([currentCall.county isEqualToString:#"W"]) {
cell.imageType1 = Washington;
}
else {
cell.imageType1 = Clackamas;
}
return cell;
}
Here is the subclassed tableviewcell:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
callView = [[UIView alloc] initWithFrame:CGRectMake(7.5, 7, 305, 65)];
[callView setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleWidth];
[callView setContentMode:UIViewContentModeTopLeft];
[callView setBackgroundColor: [UIColor colorWithRed:240.0/255.0 green:240.0/255.0 blue:240.0/255.0 alpha:1.0]];
callView.layer.borderWidth = 1.0;
callView.layer.borderColor = [UIColor colorWithRed:(0/255.0) green:(0/255.0) blue:(0/255.0) alpha:1.0].CGColor;
[self.contentView addSubview:callView];
callTypeLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 2, 190, 21)];
callTypeLabel.font = [UIFont boldSystemFontOfSize:12.0];
callTypeLabel.textColor = [UIColor blackColor];
callTypeLabel.backgroundColor = [UIColor clearColor];
callTypeLabel.highlightedTextColor = [UIColor whiteColor];
callTypeLabel.adjustsFontSizeToFitWidth = YES;
[callView addSubview:callTypeLabel];
locationLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 17 , 190, 15)];
locationLabel.font = [UIFont systemFontOfSize:10.0];
locationLabel.textColor = [UIColor blackColor];
locationLabel.backgroundColor = [UIColor clearColor];
locationLabel.highlightedTextColor = [UIColor whiteColor];
locationLabel.adjustsFontSizeToFitWidth = YES;
[callView addSubview:locationLabel];
unitsLabel = [[UILabel alloc]initWithFrame:CGRectMake(4, 43, 190, 21)];
unitsLabel.font = [UIFont systemFontOfSize:10.0];
unitsLabel.textColor = [UIColor blackColor];
unitsLabel.backgroundColor = [UIColor clearColor];
unitsLabel.highlightedTextColor = [UIColor whiteColor];
unitsLabel.adjustsFontSizeToFitWidth = NO;
[callView addSubview:unitsLabel];
stationLabel = [[UILabel alloc]initWithFrame:CGRectMake(195 , 25, 75, 20)];
stationLabel.font = [UIFont systemFontOfSize:12.0];
stationLabel.textColor = [UIColor blackColor];
stationLabel.backgroundColor = [UIColor clearColor];
stationLabel.highlightedTextColor = [UIColor whiteColor];
stationLabel.adjustsFontSizeToFitWidth = YES;
[callView addSubview:stationLabel];
CGRect countyImageFrame = CGRectMake(275, 10, 18, 18);
UIImageView *countyImageView = [[UIImageView alloc] initWithFrame:countyImageFrame];
countyImageView.image = countyImage;
[callView addSubview:countyImageView];
CGRect callTypeImageFrame = CGRectMake(275, 37, 18, 18);
UIImageView *callTypeImageView = [[UIImageView alloc] initWithFrame:callTypeImageFrame];
callTypeImageView.image = callTypeImage;
[callView addSubview:callTypeImageView];
selectionView = [[UIView alloc] initWithFrame:CGRectMake(10, 7, 200, 65)];
[selectionView setBackgroundColor: [UIColor clearColor]];
}
return self;
}
- (void)setImageType:(CallType)newImageType {
imageType = newImageType;
if (imageType == Fire) {
CGRect callTypeImageFrame = CGRectMake(275, 37, 18, 18);
UIImageView *callTypeImageView = [[UIImageView alloc] initWithFrame:callTypeImageFrame];
callTypeImageView.image = [UIImage imageNamed:#"red.png"];
[callView addSubview:callTypeImageView];
}
else if (imageType == EMS) {
CGRect callTypeImageFrame = CGRectMake(275, 37, 18, 18);
UIImageView *callTypeImageView = [[UIImageView alloc] initWithFrame:callTypeImageFrame];
callTypeImageView.image = [UIImage imageNamed:#"yellow.png"];
[callView addSubview:callTypeImageView];
}
}
- (void)setImageType1:(County)newImageType1 {
imageType1 = newImageType1;
if (imageType1 == Washington) {
CGRect callTypeImageFrame = CGRectMake(275, 10, 18, 18);
UIImageView *countyImageView = [[UIImageView alloc] initWithFrame:callTypeImageFrame];
countyImageView.image = [UIImage imageNamed:#"blue.png"];
[callView addSubview:countyImageView];
}
else if (imageType1 == Clackamas) {
CGRect callTypeImageFrame = CGRectMake(275, 10, 18, 18);
UIImageView *countyImageView = [[UIImageView alloc] initWithFrame:callTypeImageFrame];
countyImageView.image = [UIImage imageNamed:#"green.png"];
[callView addSubview:countyImageView];
}
}

This is a little subtle, but the main area your code will hang on is in the setImageType: method.
You're adding a programmatically created Image View into your view hierarchy here:
UIImageView *callTypeImageView = [[UIImageView alloc] initWithFrame:callTypeImageFrame];
callTypeImageView.image = [UIImage imageNamed:#"red.png"];
[callView addSubview:callTypeImageView];
But you never actually remove the old image view. A better way to do this might be to cache the created image view in a property of the cell, then when you set the image type, send the message -[UIView removeFromSuperview] to the old image view before creating a new one.
As your code stands now, every time a cell is dequeued, a new image view is added to it, so every time the user scrolls up and down the table view, a new image view is created and added to the cell. It won't take long for there to be dozens of image views in each cell. I suspect this is causing many times more drawRect calls into image views than is actually necessary to achieve your purpose.
A better way of doing this would be to have both types of image views as properties that you create in the cell's init method, which are only configured in the setType methods. That way you only create one image view per type, and simply set configure its image in the appropriate setType method. Doing it this way, do bear in mind that removeFromSuperview will release the imageview, so you'll have to declare it as a strong property (assuming you're using ARC).
I appreciate neither of these solutions has anything to do with Grand Central Dispatch, but hopefully that should solve your problem without using a sledgehammer to crack a nut :).

Related

UITableViewCell with subviews is not working properly

I have UITableView in my iOS app and I want to add some subviews to cell. I do it by using
[cell.contentView addSubview:someView];
and it works well, but... When I scroll down, subviews are starting to hide from cells that are on top and when I scroll back to top, they wont appear again... What I'm doing wrong? Is there some solution please?
EDIT
Mainly, I'm talking about "detailtext" label, but I have those problems in more cases...
Here is whole code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
switch (indexPath.row) {
case 0:
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
break;
default:
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
break;
}
UIView *separatorLine = [[UIView alloc] init];
separatorLine.frame = CGRectMake(15.0f, 60 - 0.5f, cell.frame.size.width-15.0f, 0.5f);
separatorLine.tag = 4;
separatorLine.backgroundColor = [UIColor lightGrayColor];
cell.layer.masksToBounds = NO;
tableView.backgroundColor = [UIColor colorWithRed:33.0 / 255.0 green:157.0 / 255.0 blue:147.0 / 255.0 alpha:1.0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIView *row2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
UIView *profileBorder = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-50, 50, 102, 102)];
profileBorder.layer.borderColor = [UIColor whiteColor].CGColor;
profileBorder.layer.borderWidth = 5; //2
profileBorder.layer.cornerRadius = 50;
NZCircularImageView *profileImage = [[NZCircularImageView alloc] initWithFrame:CGRectMake(1,1, 100, 100)];
profileImage.image = profilePhoto;
profileImage.contentMode = UIViewContentModeScaleAspectFill;
UITapGestureRecognizer *showBigProfilePhoto = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(showImage:)];
profileImage.userInteractionEnabled = YES;
[profileImage addGestureRecognizer:showBigProfilePhoto];
[profileBorder addSubview:profileImage];
UILabel *numberFeelings = [[UILabel alloc] initWithFrame:CGRectMake(10, 100-25, 100, 50)];
numberFeelings.text = [NSString stringWithFormat:#"%#\nFeelings", feelings];
numberFeelings.font = [UIFont boldSystemFontOfSize:16];
numberFeelings.textAlignment = NSTextAlignmentCenter;
numberFeelings.textColor = [UIColor whiteColor];
numberFeelings.numberOfLines = 0;
UILabel *numberFriends = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2+60, 100-25, 100, 50)];
numberFriends.text = [NSString stringWithFormat:#"%#\nFollowers", friends];
numberFriends.font = [UIFont boldSystemFontOfSize:16];
numberFriends.textColor = [UIColor whiteColor];
numberFriends.numberOfLines = 0;
numberFriends.textAlignment = NSTextAlignmentCenter;
[row2 addSubview:profileBorder];
[row2 addSubview:numberFriends];
[row2 addSubview:numberFeelings];
int rectButtons = cell.frame.size.width-246;
UIImageView *graph = [[UIImageView alloc] initWithFrame:CGRectMake(rectButtons/2, -20, 82, 82)];
UIImageView *badgets = [[UIImageView alloc] initWithFrame:CGRectMake(rectButtons/2+82, -20, 82, 82)];
UIImageView *photos = [[UIImageView alloc] initWithFrame:CGRectMake(rectButtons/2+164, -20, 82, 82)];
graph.image = [UIImage imageNamed:#"graph.jpg"];
badgets.image = [UIImage imageNamed:#"badgets.jpg"];
photos.image = [UIImage imageNamed:#"photos.jpg"];
graph.userInteractionEnabled = YES;
badgets.userInteractionEnabled = YES;
photos.userInteractionEnabled = YES;
UITapGestureRecognizer *graphTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(showGraph:)];
[graph addGestureRecognizer:graphTap];
NSArray *jmenoCasti = [name componentsSeparatedByString:#" "];
krestni = [jmenoCasti objectAtIndex:0];
int indexOfPost = indexPath.row-3;
NSMutableAttributedString *str;
int countFeeling;
int countString;
int countBeforeFeeling;
if (indexPath.row >=3) {
str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:#"%# was %#", krestni, [naladyHim objectAtIndex:[[[posts objectAtIndex:indexOfPost] objectForKey:#"_feel"] integerValue]]]];
countFeeling = [[naladyHim objectAtIndex:[[[posts objectAtIndex:indexOfPost] objectForKey:#"_feel"] integerValue]] length];
countString = krestni.length+5+countFeeling;
countBeforeFeeling = countString-countFeeling+1;
int rangeStart = countBeforeFeeling-1;
int rangeStop = str.length-rangeStart;
NSLog(#"%i ... %i", countBeforeFeeling-1, countString-1);
[str addAttribute:NSFontAttributeName value: [UIFont fontWithName:#"Helvetica-Bold" size:16.0f] range:NSMakeRange(rangeStart, rangeStop)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:32.0 / 255.0 green:147.0 / 255.0 blue:138.0 / 255.0 alpha:1.0] range:NSMakeRange(rangeStart, rangeStop)];
}
UILabel *mainText = [[UILabel alloc] initWithFrame:CGRectMake(15, 70, cell.frame.size.width-10, 20)];
mainText.attributedText = str;
UILabel *detailText;
if (!detailText) {
detailText = [[UILabel alloc] initWithFrame:CGRectMake(15, 90, cell.frame.size.width-10, 30)];
}
detailText.textColor = [UIColor grayColor];
detailText.font = [UIFont systemFontOfSize:13];
switch (indexPath.row) {
case 0:
cell.textLabel.textAlignment = NSTextAlignmentCenter;
cell.textLabel.text = name;
cell.textLabel.textColor = [UIColor whiteColor];
cell.textLabel.font = [UIFont systemFontOfSize:20];
cell.backgroundColor = [UIColor clearColor];
break;
case 1:
[cell.contentView addSubview:row2];
cell.backgroundColor = [UIColor clearColor];
break;
case 2:
cell.backgroundColor = [UIColor colorWithRed:236.0 / 255.0 green:235.0 / 255.0 blue:210.0 / 255.0 alpha:1.0];
[cell.contentView addSubview:graph];
[cell.contentView addSubview:badgets];
[cell.contentView addSubview:photos];
break;
default:
detailText.text = [[posts objectAtIndex:indexPath.row-3] objectForKey:#"_text"];
[cell.contentView addSubview:detailText];
cell.textLabel.attributedText = str;
cell.backgroundColor = [UIColor colorWithRed:236.0 / 255.0 green:235.0 / 255.0 blue:210.0 / 255.0 alpha:1.0];
break;
}
return cell; }
This is an easy way thats works for me:
for(UIView *subview in cell.contentView.subviews)
{
if([subview isKindOfClass: [UIView class]])
{
[subview removeFromSuperview];
}
}
You can use it at the begin of
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
In your tableView:cellForRowAtIndexPath:, you hide the info when you don't want it to be shown, but you don't explicitly unhide it for cells where it should be shown.
Look at the first two lines in that method: What you are - correctly - doing is reusing your cells, so when cells are scrolled out of view, they are removed from the UITableView and put into the reuse queue. Then, when cells should become visible, the TableView gets cells from that queue - or creates new ones if none are available.
This all goes very well, but after a while, cells with hidden info buttons are put on the queue. And then, some time later, those cells are reused - and sometimes for rows in which there should be info visible.
There are two solutions to this: You could either explicitly unhide the information for those rows where you want it to be shown, or you could use two different kinds of cell, one with hidden info, and one with visible info. You then give each of those cells a different identifier, and based on what row the cells are in, set the identifier before dequeuing/creating cells.
You should create a subclass of UITableViewCell for each different cell and add all your view related code that doesn't change depending on the data into an initialization method. Then create a method in each cell called something like configureWithData and pass in the data relevant to the cell. The creation of your attributed string and modification of label frames can occur in this configuration method.
It will dramatically reduce the clutter in your UITableViewController and is much better design wise. There is no real need for your view controller to know what your table cells look like.
Here is an example of what I am talking about:
-(void)awakeFromNib
{
if( self.accessoryType == UITableViewCellAccessoryDisclosureIndicator )
{
DTCustomColoredAccessory *accessory = [DTCustomColoredAccessory accessoryWithColor:[UIColor whiteColor]];
accessory.highlightedColor = [UIColor blackColor];
self.accessoryView = accessory;
}
}
-(void)configureCellWithObject:(id)inObject
{
TableDataModel *dataObject = (TableDataModel *)inObject;
self.titleLabel.text = dataObject.titleString;
self.subtitleLabel.text = dataObject.subtitleString;
self.accessibilityIdentifier = dataObject.accessIdString;
if( dataObject.imageUrlString != nil )
{
UIImage *iconImage = [UIImage imageNamed:dataObject.imageUrlString];
if( iconImage != nil )
{
NSInteger yOffset = [StaticTools centerYOffset:self.frame.size objectFrameSize:iconImage.size];
self.iconImageView.image = iconImage;
CGRect frame = self.iconImageView.frame;
frame.origin.y = yOffset;
frame.size = iconImage.size;
[self.iconImageView setFrame:frame];
}
else
{
[self.iconImageView loadImageFromUrl:dataObject.imageUrlString];
}
}
}

Adjusting Cell fields - Objective C

I have a dynamically set table view controller that is used to populate a news type feed. I am having trouble connecting one class to the other for setting the text, image, etc... of that current cell.
Here is the gist:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"timelineCell";
FBGTimelineCell *cell = (FBGTimelineCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.text = [self.googlePlacesArrayFromAFNetworking[indexPath.row] objectForKey:#"message"]; <!-- here is where I want to for example, set the title to the message within this array.
if (!cell)
{
cell = [[FBGTimelineCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell initTimelineCell];
}
UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:#"%d.jpg", indexPath.row]];
cell.photoView.image = img;
return cell;
}
Here is the FBH... init function:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
cellContentView = [[UIView alloc] initWithFrame:CGRectMake(10, 5, 300, 440)];
cellContentView.backgroundColor = [UIColor whiteColor];
photoView = [[FBGTimelinePhotoView alloc] initWithFrame:CGRectMake(5, 102, 310, 310)];
photoView.backgroundColor = [UIColor darkGrayColor];
[photoView setUserInteractionEnabled:YES];
UIView *profilePic = [[UIView alloc] initWithFrame:CGRectMake(9, 9, 30, 30)];
profilePic.backgroundColor = [UIColor darkGrayColor];
UILabel *usernameLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 9, 222, 18)];
usernameLabel.font = [UIFont systemFontOfSize:14.0];
usernameLabel.text = #"Username";
UILabel *timestampLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 25, 222, 17)];
timestampLabel.font = [UIFont systemFontOfSize:12.0];
timestampLabel.text = #"3 hours ago";
timestampLabel.textColor = [UIColor lightGrayColor];
UILabel *statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(9, 50, 283, 41)];
statusLabel.font = [UIFont systemFontOfSize:15.0];
statusLabel.text = #"Status..status..status..status..status..status..status..status..status..status..status..status..status..status..status..";
statusLabel.numberOfLines = 2;
statusLabel.lineBreakMode = NSLineBreakByWordWrapping;
UILabel *likeLabel = [[UILabel alloc] initWithFrame:CGRectMake(9, 413, 32, 21)];
likeLabel.font = [UIFont systemFontOfSize:13.0];
likeLabel.text = #"Like";
UILabel *commentLabel = [[UILabel alloc] initWithFrame:CGRectMake(113, 413, 74, 21)];
commentLabel.font = [UIFont systemFontOfSize:13.0];
commentLabel.text = #"Comment";
UILabel *shareLabel = [[UILabel alloc] initWithFrame:CGRectMake(246, 413, 46, 21)];
shareLabel.font = [UIFont systemFontOfSize:13.0];
shareLabel.text = #"Share";
[self addSubview:cellContentView];
[self addSubview:photoView];
[cellContentView addSubview:profilePic];
[cellContentView addSubview:usernameLabel];
[cellContentView addSubview:timestampLabel];
[cellContentView addSubview:statusLabel];
[cellContentView addSubview:likeLabel];
[cellContentView addSubview:commentLabel];
[cellContentView addSubview:shareLabel];
}
return self;
}
So I need to be able to set the cell text and different views within the cell within the cellForRowAtIndexPath if possible for each cell that is set up in the FB..init function.
Suggestions, thoughts?
You should create properties (in the FBGTimelineCell class) for each of the UI elements that you need to access in cellFroRowAtIndexPath, then you can access them with cell.propertyName.
You can create properties for all the dynamic values which are expected to be changed with each cell. Those properties you can set in your cellForRowAtIndexPath method.
eg. cell.statusText = [NSString stringWithFormat:#"%# is rocking!!", indexPath.row];
Public properties like statusText you can add all the UIElements expecting to be dynamically added.
Hope it helps.
Cheers.

Header image not resizable in expandable table

I am pretty new to Xcode and this simple problem has been driving me mad! I have created an expandable table that works fine. This is some of the code on a UIView subclass for the section that expands when you tap on a cell:
- (id)initWithFrame:(CGRect)frame WithTitle: (NSString *) title Section:(NSInteger)sectionNumber delegate: (id <SectionView>) Delegate
{
self = [super initWithFrame:frame];
if (self) {
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(discButtonPressed:)];
[self addGestureRecognizer:tapGesture];
self.userInteractionEnabled = YES;
self.section = sectionNumber;
self.delegate = Delegate;
CGRect LabelFrame = CGRectMake(100, 100, 100, 100);
LabelFrame.size.width -= 100;
CGRectInset(LabelFrame, 1.0, 1.0);
//BUTTON
CGRect buttonFrame = CGRectMake(LabelFrame.size.width, 0, 100, LabelFrame.size.height);
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = buttonFrame;
//[button setImage:[UIImage imageNamed:#"carat.png"] forState:UIControlStateNormal];
//[button setImage:[UIImage imageNamed:#"carat-open.png"] forState:UIControlStateSelected];
[button addTarget:self action:#selector(discButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
self.discButton = button;
//My IMAGE
NSString *imageName = #"gradient1.png";
UIImage *myImage = [UIImage imageNamed:imageName];
UIImageView *sectionHeaderView = [[UIImageView alloc] initWithImage:myImage];
UIImageView *imageView = [[UIImageView alloc] initWithImage:myImage];
imageView.frame = CGRectMake(20,50,100,100);
[self addSubview:sectionHeaderView];
self.headerBG = sectionHeaderView;
//HEADER LABEL
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(22, 12, sectionHeaderView.frame.size.width, 35.0)];
label.textAlignment = NSTextAlignmentLeft;
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor whiteColor];
label.shadowColor = [UIColor darkGrayColor];
label.shadowOffset = CGSizeMake(0.0, -1.0);
label.text = title;
label.font = [UIFont fontWithName:#"AvenirNext-Bold" size:20.0];
sectionHeaderView.backgroundColor = [UIColor clearColor];
//label.textAlignment = UITextAlignmentLeft;
[self addSubview:label];
self.sectionTitle = label;
}
return self;
}
I have a custom image on the cell #"gradient1.png" but I don't seem to be able to resize it? Here is the header code in the UITableViewController:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection: (NSInteger)section
{
SectionInfo *array = [self.sectionInfoArray objectAtIndex:section];
if (!array.sectionView)
{
NSString *title = array.category.name;
array.sectionView = [[SectionView alloc] initWithFrame:CGRectMake(0, 10, self.tableView.bounds.size.width, 0) WithTitle:title Section:section delegate:self];
}
return array.sectionView;
}
Sorry if this is a trivial question, your help is greatly appreciated!
I don't see where you are trying to resize the image so I can't offer any help in why it is not resizing, but I found this confusing:
//My IMAGE
NSString *imageName = #"gradient1.png";
UIImage *myImage = [UIImage imageNamed:imageName];
UIImageView *sectionHeaderView = [[UIImageView alloc] initWithImage:myImage];
UIImageView *imageView = [[UIImageView alloc] initWithImage:myImage];
imageView.frame = CGRectMake(20,50,100,100);
[self addSubview:sectionHeaderView];
self.headerBG = sectionHeaderView;
In this part of code you create two imageviews, then you resize one and add the other to the cell (I'm assuming cell) subviews. Is it possible that you are trying to resize the view that you never added as a subview of the cell?
Also, resizing should happen inside - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath.
Make sure that you are resizing the proper view, ten make sure you are resizing it in the proper place.

iOS how to add UIView to tableview cell effectively

I have a table going where each cell has a UIView in it that is fed from an XMLParser feed. If I leave it how it is, each time I refresh the views build upon each other because they are not getting released/removed, which makes total sense. How would I go about writing my code to avoid that problem, and not having to rebuild the view's each time I refresh. I am stuck in the logic of it and also the actual syntax. Thanks.
Code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
JointCAD *currentCall = [[xmlParser calls] objectAtIndex:indexPath.row];
self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"texture.png"]];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UIView *selectionView = [[UIView alloc] initWithFrame:CGRectMake(10, 7, 200, 65)];
[selectionView setBackgroundColor: [UIColor clearColor]];
cell.selectedBackgroundView = selectionView;
}
// Display content in each cell
cellSeparator = [[UIView alloc] initWithFrame:CGRectMake(10, 7, 300, 65)];
[cellSeparator setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleWidth];
[cellSeparator setContentMode:UIViewContentModeTopLeft];
[cellSeparator setBackgroundColor: [UIColor colorWithRed:240.0/255.0 green:240.0/255.0 blue:240.0/255.0 alpha:1.0]];
cellSeparator.layer.borderWidth = 1.0;
cellSeparator.layer.borderColor = [UIColor blackColor].CGColor;
[cell addSubview:cellSeparator];
callTypeLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 2, 190, 21)];
callTypeLabel.text = [currentCall currentCallType];
callTypeLabel.backgroundColor = [UIColor clearColor];
callTypeLabel.font = [UIFont boldSystemFontOfSize:12.0];
[cellSeparator addSubview:callTypeLabel];
locationLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, 17 , 190, 15)];
locationLabel.text = [currentCall location];
locationLabel.backgroundColor = [UIColor clearColor];
locationLabel.font = [UIFont systemFontOfSize:10.0];
[cellSeparator addSubview:locationLabel];
unitsLabel = [[UILabel alloc]initWithFrame:CGRectMake(4, 43, 190, 21)];
unitsLabel.text = [currentCall units];
unitsLabel.backgroundColor = [UIColor clearColor];
unitsLabel.font = [UIFont italicSystemFontOfSize:10.0];
[cellSeparator addSubview:unitsLabel];
stationLabel = [[UILabel alloc]initWithFrame:CGRectMake(195 , 25, 75, 20)];
NSString *station = [#"Station: " stringByAppendingString:currentCall.station];
stationLabel.text = station;
stationLabel.backgroundColor = [UIColor clearColor];
stationLabel.font = [UIFont boldSystemFontOfSize:11.0];
[cellSeparator addSubview:stationLabel];
if ([currentCall.county isEqualToString:#"W"]) {
UIImage *countyImage = [UIImage imageNamed:#"blue.png"];
CGRect countyImageFrame = CGRectMake(275, 10, 18, 18);
UIImageView *countyImageLabel = [[UIImageView alloc] initWithFrame:countyImageFrame];
countyImageLabel.image = countyImage;
[cellSeparator addSubview:countyImageLabel];
} else {
UIImage *countyImage = [UIImage imageNamed:#"green.png"];
CGRect countyImageFrame = CGRectMake(275, 10, 18, 18);
UIImageView *countyImageLabel = [[UIImageView alloc] initWithFrame:countyImageFrame];
countyImageLabel.image = countyImage;
[cellSeparator addSubview:countyImageLabel];
}
if ([currentCall.callType isEqualToString:#"F"]) {
UIImage *callTypeImage = [UIImage imageNamed:#"red.png"];
CGRect callTypeImageFrame = CGRectMake(275, 37, 18, 18);
UIImageView *callTypeImageLabel = [[UIImageView alloc] initWithFrame:callTypeImageFrame];
callTypeImageLabel.image = callTypeImage;
[cellSeparator addSubview:callTypeImageLabel];
} else {
UIImage *callTypeImage = [UIImage imageNamed:#"yellow.png"];
CGRect callTypeImageFrame = CGRectMake(275, 37, 18, 18);
UIImageView *callTypeImageLabel = [[UIImageView alloc] initWithFrame:callTypeImageFrame];
callTypeImageLabel.image = callTypeImage;
[cellSeparator addSubview:callTypeImageLabel];
}
return cell;
}
If I understand your question correctly, I think the solution you want is to subclass UITableViewCell, set up your subviews (UIImageViews and all that) and make them properties on your subclass. Then you can
if (!cell.imageView) {
cell.imageView = [[UIImageView alloc] initWithFrame:myFrame];
}
then just set the image. That way you're sure to not stack image views on top of one another and the correct image will get set when the cell is dequeued.
EDIT:
Make a class called MyTableViewCell (or whatever you want to call it but make sure it's a subclass of UITableViewCell)
Add #property (strong, nonatomic) UIImageView *imageView;
Then use MyTableViewCell instead of UITableViewCell in you cellForRowAtIndexPath and you can access the image property of your custom table view cell, check if it exists, if not create it (which is what the above code does) and then set the image. I would give you code but I'm on my phone. Google subclassing UITableviewCell. You should find a ton of examples.

Slow loading tableview on iPhone with reusable cells

I load the data from Parse.com backend, they send me a solutions for use the reusable cells but now I still have troubles with the loading speed, this is the coding I have in my tableview and I have a Subclass for making up my cells (ExploreStreamCustomCell.m)
- (ExploreStreamCustomCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
object:(PFObject *)object
{
static NSString *CellIdentifier = #"ExploreStreamCustomCell";
ExploreStreamCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[ExploreStreamCustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
// Configure the cell
cell.listItemTitle.text = [object objectForKey:#"text"];
cell.checkinsLabel.text = [NSString stringWithFormat:#"%#", [object objectForKey:#"checkins"]];
cell.descriptionLabel.text = [object objectForKey:#"description"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
PFFile *listThumbnail = [object objectForKey:#"header"];
cell.listViewImage.image = [UIImage imageNamed:#"loading_image_stream.png"]; // placeholder image
cell.listViewImage.file = listThumbnail;
[cell.listViewImage loadInBackground:NULL];
return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForNextPageAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [super tableView:tableView cellForNextPageAtIndexPath:indexPath];
cell.textLabel.font = [cell.textLabel.font fontWithSize:kPAWWallPostTableViewFontSize];
return cell;
}
If I have all the content of the //configure cell in the cell == nil the it's fast but it show up 3 of the 9 unique datarows and repeat those 3 unique content cell 3 times?
Edit extra code within ExploreStreamCustomCell.m
#import "ExploreStreamCustomCell.h"
#implementation ExploreStreamCustomCell
#synthesize listViewImage,
iconLocation,
iconPeople,
iconCheckins,
listItemTitle,
locationLabel,
peopleLabel,
checkinsLabel,
descriptionLabel,
listItemView;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]){
//Initialization code
listItemView = [[UIView alloc] init];
listViewImage = [[PFImageView alloc] init];
iconLocation = [[UIImageView alloc] init];
iconPeople = [[UIImageView alloc] init];
iconCheckins = [[UIImageView alloc] init];
listItemTitle = [[UILabel alloc] init];
locationLabel = [[UILabel alloc] init];
peopleLabel = [[UILabel alloc] init];
checkinsLabel = [[UILabel alloc] init];
descriptionLabel = [[UILabel alloc] init];
listViewImage.image = [UIImage imageNamed:#"nachtwacht_list_formaat.png"];
iconLocation.image = [UIImage imageNamed:#"icon_magenta_location.png"];
iconPeople.image = [UIImage imageNamed:#"icon_magenta_people.png"];
iconCheckins.image = [UIImage imageNamed:#"icon_magenta_checkins.png"];
listItemTitle.text = #"text";
locationLabel.text = #"0,7 km";
peopleLabel.text = #"34";
checkinsLabel.text = #"61";
descriptionLabel.text = #"Description text.";
[self.contentView addSubview:listItemView];
[self.contentView addSubview:listViewImage];
[self.contentView addSubview:iconLocation];
[self.contentView addSubview:iconPeople];
[self.contentView addSubview:iconCheckins];
[self.contentView addSubview:listItemTitle];
[self.contentView addSubview:locationLabel];
[self.contentView addSubview:peopleLabel];
[self.contentView addSubview:checkinsLabel];
[self.contentView addSubview:descriptionLabel];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
CGRect contentRect = self.contentView.bounds;
CGFloat boundsX = contentRect.origin.x;
CGRect frame;
frame= CGRectMake(boundsX+0 , 33, 280, 124);
listViewImage.frame = frame;
listViewImage.contentMode = UIViewContentModeScaleAspectFill;
listViewImage.layer.masksToBounds = YES;
//listViewImage.backgroundColor = [UIColor lightGrayColor];
frame= CGRectMake(boundsX+20 , 164, 12, 18);
iconLocation.frame = frame;
//iconLocation.backgroundColor = [UIColor lightGrayColor];
frame= CGRectMake(boundsX+102 , 164, 24, 18);
iconPeople.frame = frame;
//iconPeople.backgroundColor = [UIColor lightGrayColor];
frame= CGRectMake(boundsX+193 , 164, 20, 16);
iconCheckins.frame = frame;
//iconLocation.backgroundColor = [UIColor lightGrayColor];
frame= CGRectMake(boundsX+0 , 0, 280, 33);
listItemView.frame = frame;
listItemView.backgroundColor = [UIColor colorWithRed:0.749 green:0.000 blue:0.243 alpha:1.000];
frame= CGRectMake(boundsX+20 , 3, 240, 29);
listItemTitle.frame = frame;
//listItemTitle.textColor = [UIColor colorWithRed:250.0f/255.0f green:194.0f/255.0f blue:9.0f/255.0f alpha:0.8f];
listItemTitle.textAlignment = UITextAlignmentLeft;
listItemTitle.font = [UIFont boldSystemFontOfSize:15];
listItemTitle.textColor = [UIColor whiteColor];
listItemTitle.backgroundColor = [UIColor clearColor];
listItemTitle.lineBreakMode = UILineBreakModeTailTruncation;
//listItemTitle.backgroundColor = [UIColor orangeColor];
frame= CGRectMake(boundsX+40 , 164, 57, 21);
locationLabel.frame = frame;
locationLabel.textAlignment = UITextAlignmentLeft;
locationLabel.font = [UIFont boldSystemFontOfSize:12];
locationLabel.textColor = [UIColor colorWithRed:0.749 green:0.000 blue:0.243 alpha:1.000];
locationLabel.backgroundColor = [UIColor clearColor];
locationLabel.lineBreakMode = UILineBreakModeTailTruncation;
locationLabel.numberOfLines = 1;
//locationLabel.backgroundColor = [UIColor redColor];
frame= CGRectMake(boundsX+134 , 164, 57, 21);
peopleLabel.frame = frame;
peopleLabel.textAlignment = UITextAlignmentLeft;
peopleLabel.font = [UIFont boldSystemFontOfSize:12];
peopleLabel.textColor = [UIColor colorWithRed:0.749 green:0.000 blue:0.243 alpha:1.000];
peopleLabel.backgroundColor = [UIColor clearColor];
peopleLabel.lineBreakMode = UILineBreakModeTailTruncation;
peopleLabel.numberOfLines = 1;
frame= CGRectMake(boundsX+221 , 164, 51, 21);
checkinsLabel.frame = frame;
checkinsLabel.textAlignment = UITextAlignmentLeft;
checkinsLabel.font = [UIFont boldSystemFontOfSize:12];
checkinsLabel.textColor = [UIColor colorWithRed:0.749 green:0.000 blue:0.243 alpha:1.000];
checkinsLabel.backgroundColor = [UIColor clearColor];
checkinsLabel.lineBreakMode = UILineBreakModeTailTruncation;
checkinsLabel.numberOfLines = 1;
frame= CGRectMake(boundsX+0 , 189, 280, 55);
descriptionLabel.frame = frame;
descriptionLabel.textAlignment = UITextAlignmentLeft;
descriptionLabel.font = [UIFont systemFontOfSize:13];
descriptionLabel.backgroundColor = [UIColor clearColor];
descriptionLabel.lineBreakMode = UILineBreakModeTailTruncation;
descriptionLabel.numberOfLines = 3;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
/*
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
#end
A great way to explore the inefficiencies of your code is to use Instruments' Time Profiler tool. The Time Profiler will let you see how much time is being spent on each task, line-by-line in your code.
I would recommend the following settings for profiling:
From Apple's Face Detection sample app:
You can then double click any line (higher percentages mean more time is being devoted to that method call) to see in the code how much time is spent in each place.
From here you can begin to figure out where you are being inefficient and see exactly what is taking up so much time. Good luck!

Resources