selector for multiple uibuttons in uitableviewcell - ios

I'm adding the same selector for multiple UIButtons which are part of a UITableViewCell and it works only for the first one. Am I missing something?
Here's my code:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
NSDictionary *d = [tableData objectAtIndex:indexPath.row];
NSArray *answers = [d objectForKey:#"answers"];//array of { id = 35; text = "\U03c4\U03a\U03c0\U03bf\U03c4\U03b1"; }
UILabel *startDate = (UILabel *)[cell viewWithTag:100];
long long startDateEpoch = [[d objectForKey:#"startDate"] longLongValue];
NSDate *sDate = [NSDate dateWithTimeIntervalSince1970:startDateEpoch/1000];
NSDateFormatter *startDateFormatter = [[NSDateFormatter alloc] init];
[startDateFormatter setDateFormat:#"dd/MM/yyyy"];
startDate.text = [startDateFormatter stringFromDate:sDate];
((UILabel *)[cell viewWithTag:101]).text = [d objectForKey:#"subject"];
NSArray *tags = [d objectForKey:#"tags"];
((UILabel *)[cell viewWithTag:102]).text = [tags componentsJoinedByString:#" "];
NSString *imageURL = [d objectForKey:#"media"];
UIImageView *iv = (UIImageView *)[cell viewWithTag:103];
iv.contentMode = UIViewContentModeScaleAspectFit;
[iv sd_setImageWithURL:[NSURL URLWithString:imageURL]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
UIView *buttonsContainer = (UIView *)[cell viewWithTag:104];
for(UIView *vv in buttonsContainer.subviews){
[vv removeFromSuperview];
}
int index = 0;
NSLog(#"buttonsContainer children: %d", buttonsContainer.subviews.count);
for(NSDictionary *answer in answers){
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, index * 40 + (index+1)*5, [UIScreen mainScreen].bounds.size.width, 40)];
v.backgroundColor = [UIColor whiteColor];
CGRect labelFrame = v.frame;
labelFrame.origin.y = 0;
UILabel *l = [[UILabel alloc] initWithFrame:labelFrame];
l.text = (NSString *)[answer objectForKey:#"text"];
l.textAlignment = NSTextAlignmentCenter;
UIView *bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, v.frame.size.height - 1, v.frame.size.width, 1)];
bottomLine.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:205.0/255.0 blue:103.0/255.0 alpha:1.0];
UIButton *b = [[UIButton alloc] initWithFrame:v.frame];
[b addTarget:self action:#selector(answered:) forControlEvents:UIControlEventTouchUpInside];
[v addSubview:l];
[v addSubview:bottomLine];
[v addSubview:b];
[buttonsContainer addSubview:v];
index++;
}
}
So for example if 4 buttons are added, the selector is called only when I click on the first one. When I click on the other three nothing happens.
EDIT:
adding the answered: code:
- (void)answered:(UIButton *)sender
{
NSLog(#"#answered");
}

ok, I found it. Many cudos to TomSwift since his point gave me the idea to place borders on all the views in order to debug their frames size and origin.
Notice that I give to my buttons the same frame as their superviews, which is wrong since they should not have the same origin. The buttons' origin should be 0,0 since they have the same frame size as their superviews.
lessons learn for noobs like me:
When a button does not work, place borders in order to make sure their frame is within the superview's bounds.
Do not assign the same frame on a view and its subview. It will place it outside of the superview's bounds which in 92% of the cases brings undesirable behaviour.

Related

Xcode and tag searching

A simple inquiry.
When using Objective-C / Swift and one decides to implement tags for objects within the storyboard, how does the system search for the tags?
Does it approach this as a linear search? Therefore, implying that tags with a lower number value will be faster to search for? Or does it approach this entirely differently?
For example:
UIImageView *imageView = (UIImageView *)[self viewWithTag:1];
imageView.image = [UIImage imageNamed: #"Elderberries"];
vs
UIImageView *imageView = (UIImageView *)[self viewWithTag:100000000];
imageView.image = [UIImage imageNamed: #"Motherless_Goat"];
Thanks
I did some experiment, below is the code
//adding 30000 tag at first position
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
label.text = [NSString stringWithFormat:#"%d", 30000];
label.tag = 30000;
[self.view addSubview:label];
for (int i = 0; i < 30000; i++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
label.text = [NSString stringWithFormat:#"%d", i];
label.tag = i;
[self.view addSubview:label];
}
NSTimeInterval currentTime, fetchTime;
currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label1 = (UILabel *)[self.view viewWithTag:5];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(#"Label:%# = %f",label1.text, fetchTime - currentTime);
currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label2 = (UILabel *)[self.view viewWithTag:100];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(#"Label:%# = %f",label2.text, fetchTime - currentTime);
currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label3 = (UILabel *)[self.view viewWithTag:1000];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(#"Label:%# = %f",label3.text, fetchTime - currentTime);
currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label4 = (UILabel *)[self.view viewWithTag:5000];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(#"Label:%# = %f",label4.text, fetchTime - currentTime);
currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label5 = (UILabel *)[self.view viewWithTag:10000];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(#"Label:%# = %f",label5.text, fetchTime - currentTime);
currentTime = CFAbsoluteTimeGetCurrent();
UILabel *label6 = (UILabel *)[self.view viewWithTag:30000];
fetchTime = CFAbsoluteTimeGetCurrent();
NSLog(#"Label:%# = %f",label6.text, fetchTime - currentTime);
And below were the logs (reformatted so that comparison is easy)
Label:5 = 0.000011
Label:100 = 0.000043
Label:1000 = 0.000346
Label:5000 = 0.001169
Label:10000 = 0.002115
Label:30000 = 0.000009
Conclusion:
The viewWithTag: will take more time for higher tags (only if there are large number of objects), it might be possible that search is linear which I think is the case because view.subViews gives you the array in the order they are added not by the tag. Yes it takes more time and it almost work as linear search.
The time depends upon the index at which subview was added, in the above case time for 30000 tag is minimum than all other tags because it was added at first index.
The posible implementation of viewWithTag: could be like this
- (UIView *)viewWithTag:(NSInteger)tag {
for (UIView *view in self.subviews) {
if (view.tag == tag) {
return view;
}
}
return nil;
}

UITableViewCell Duplicate Behavior With UIButton SetTitle And Cell Reuse?

I'm getting some really unusual behavior with my application. I have a tableview that loads cells based on data from a server, The data coming from the server is great, no duplicates and is how it should be. However as I scroll through my table I'm noticing UIButtons that I use setTitle on are showing duplicate title that were previously shown while scrolling, as if the reused cells aren't updating the title in some cases when setTitle is called..
UITableViewCell *cell = [self dequeueReusableCellWithIdentifier:DETAILED_TAGS_FEED_CELL_IDENTIFIER];
NSDictionary *tag = [self.tags objectAtIndex:indexPath.row];
ArgumentButton *nameButton = (ArgumentButton *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_NAME];
[nameButton addTarget:self action:#selector(tagSelected:) forControlEvents:UIControlEventTouchUpInside];
[nameButton setTitle:[NSString stringWithFormat:#"#%#", [tag objectForKey:#"tag"]] forState:UIControlStateNormal];
nameButton.argument = [tag objectForKey:#"tag"];
UILabel *totalFollowersLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_TOTAL_FOLLOWERS];
totalFollowersLabel.text = [tag objectForKey:#"followers"];
UILabel *followersLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_FOLLOWERS];
UIView *dividerView = (UIView *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_DIVIDER];
UILabel *totalProductsLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_TOTAL_PRODUCTS];
totalProductsLabel.text = [tag objectForKey:#"products"];
UILabel *productsLabel = (UILabel *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_PRODUCTS];
if (self.allowFollow) {
totalFollowersLabel.frame = CGRectMake(30, totalFollowersLabel.frame.origin.y, totalFollowersLabel.frame.size.width, totalFollowersLabel.frame.size.height);
followersLabel.frame = CGRectMake(30, followersLabel.frame.origin.y, followersLabel.frame.size.width, followersLabel.frame.size.height);
dividerView.frame = CGRectMake(133, dividerView.frame.origin.y, dividerView.frame.size.width, dividerView.frame.size.height);
totalProductsLabel.frame = CGRectMake(157, totalProductsLabel.frame.origin.y, totalProductsLabel.frame.size.width, totalProductsLabel.frame.size.height);
productsLabel.frame = CGRectMake(157, productsLabel.frame.origin.y, productsLabel.frame.size.width, productsLabel.frame.size.height);
NSString *followButtonTitle = ([[tag objectForKey:#"followed"] isEqualToString:#"1"]) ? #"Unfollow" : #"Follow";
ArgumentButton *followButton = (ArgumentButton *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_FOLLOW];
followButton.argument = indexPath;
[followButton addTarget:self action:#selector(followSelected:) forControlEvents:UIControlEventTouchUpInside];
[followButton setTitle:followButtonTitle forState:UIControlStateNormal];
followButton.hidden = NO;
}
HorizontalScroll *scroll = (HorizontalScroll *)[cell viewWithTag:DETAILED_TAGS_FEED_CELL_TAG_SCROLL];
scroll.contentOffset = CGPointMake(-5, 0);
scroll.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
scroll.pagingEnabled = NO;
[scroll resetItems];
NSArray *items = [tag objectForKey:#"items"];
NSMutableArray *scrollItems = [[NSMutableArray alloc] init];
for (NSDictionary *item in items) {
NSArray *scrollItemXIB = [[NSBundle mainBundle] loadNibNamed:#"DetailedFeedScrollItemView" owner:self options:nil];
UIView *scrollItemView = [scrollItemXIB lastObject];
ArgumentButton *itemButton = (ArgumentButton *)[scrollItemView viewWithTag:DETAILED_FEED_SCROLL_ITEM_TAG_BUTTON];
[itemButton sd_setImageWithURL:[APIController resourceUrlForUserId:[item objectForKey:#"userId"] resourceName:[item objectForKey:#"thumbnail"]] forState:UIControlStateNormal];
[itemButton addTarget:self action:#selector(productSelected:) forControlEvents:UIControlEventTouchUpInside];
itemButton.argument = [item objectForKey:#"id"];
[scrollItems addObject:scrollItemView];
}
[scroll loadItems:scrollItems];
return cell;
Note: I am using UITableViewCells within their own XIB for this, which is set like this in viewDidLoad.
[self registerNib:[UINib nibWithNibName:#"DetailedTagsFeedTableViewCell" bundle:nil] forCellReuseIdentifier:DETAILED_TAGS_FEED_CELL_IDENTIFIER];
It's as if [nameButton setTitle:] is not setting the right titles while scrolling? I've tried a little debugging by setting the followersLabel text equal to the same value that we're attempting to set with setTitle on the nameButton, and the value IS correct when setting the .text property of the label in the same cell.. Very confusing.
The Argument button class is nothing special. Just a simple subclass that has a public property for passing an argument with itself to a target/action.

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];
}
}
}

UICollectionView poor scrolling performance

The problem I encounter is that whenever a row goes out of view, the scroll has a very fast and short lag.
This is my code:
- (UICollectionViewCell *)collectionView:(UICollectionView *)_collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [self.collView dequeueReusableCellWithReuseIdentifier:#"cell" forIndexPath:indexPath];
Saints *note = nil;
int aX=0;
int aY=0;
note = [self.fetchedResultsController objectAtIndexPath:indexPath];
for (UIView *view in cell.contentView.subviews) {
if([view isKindOfClass:[UIImageView class]])
{
[view removeFromSuperview];
}
else if([view isKindOfClass:[UILabel class]])
{
[view removeFromSuperview];
}}
cell.backgroundColor = [UIColor clearColor];
UIImage *imgbackground = [UIImage imageNamed:#"today-left-side-images-bg.png"];
NSArray *messages = [[NSArray alloc] initWithObjects: #"random-saint-text-bg-brown.png",#"random-saint-text-bg-brightblue.png",#"random-saint-text-bg-green.png",#"random-saint-text-bg-grey.png",#"random-saint-text-bg-lightblue.png",#"random-saint-text-bg-lime.png",#"random-saint-text-bg-purple.png",#"random-saint-text-bg-red.png",#"random-saint-text-bg-teal.png",nil];
int randNum = arc4random() % [messages count];
NSString *returnValue = [messages objectAtIndex:randNum];
NSString *rndBGImg= returnValue;
UIImage *imgbackgroundlower = [UIImage imageNamed:rndBGImg];
UIImageView *imgViewlower = [[UIImageView alloc] initWithImage:imgbackgroundlower];
//imgViewlower.frame=CGRectMake(aX, aY+140, 140,73);
imgViewlower.frame=CGRectMake(aX+4, aY+114, 119,43);
UIImageView *imgView = [[UIImageView alloc] initWithImage:imgbackground];
imgView.frame=CGRectMake(aX, aY, 127,162);
UIImageView *imgSaintPic = [[UIImageView alloc]init];
imgSaintPic.tag=1;
imgSaintPic.frame=CGRectMake(aX+6, aY+6, 114,145);
//NSString *imgname = [aDic objectForKey:#"saint_image"];
NSString *imgname = note.saint_imagethumbnail;
UIImage *tempimg= [UIImage imageNamed:imgname];
[imgSaintPic setImage:tempimg];
UILabel *lblNamelocal=[[UILabel alloc]init];
NSString *strSaintName=note.saint_name;
//lblNamelocal.text=strSaintName;
if([note.saint_title length]>1)
lblNamelocal.text=[NSString stringWithFormat:#"%# %#",note.saint_title,strSaintName];
else
lblNamelocal.text=[NSString stringWithFormat:#"%#",strSaintName];
//lblNamelocal.frame = CGRectMake(aX+6, aY+109, 116,30);
[lblNamelocal sizeToFit];
lblNamelocal.frame = CGRectMake(aX+5, aY+115, 118,26);
lblNamelocal.lineBreakMode = UILineBreakModeWordWrap;
lblNamelocal.numberOfLines = 0;
lblNamelocal.backgroundColor = [UIColor clearColor];
lblNamelocal.textColor = [UIColor whiteColor];
lblNamelocal.font = [UIFont fontWithName:#"HelveticaNeue-CondensedBold" size:11 ];
// lblNamelocal.textAlignment=UITextAlignmentLeft;
lblNamelocal.baselineAdjustment = UIBaselineAdjustmentAlignCenters;
lblNamelocal.shadowColor = [UIColor darkGrayColor];
lblNamelocal.shadowOffset = CGSizeMake(0,0.5);
lblNamelocal.textAlignment = UITextAlignmentCenter;
UILabel *lblsubtitle=[[UILabel alloc]init];
//NSString *strSaintSubtitle=[aDic objectForKey:#"saint_title"];
lblsubtitle.text=note.saint_subtitle;
//lblsubtitle.frame = CGRectMake(aX+6, aY+132, 116, 25);
lblsubtitle.frame = CGRectMake(aX+5, aY+140, 113, 20);
lblsubtitle.lineBreakMode = UILineBreakModeWordWrap;
lblsubtitle.numberOfLines = 2;
lblsubtitle.backgroundColor = [UIColor clearColor];
lblsubtitle.textColor = [UIColor whiteColor];
lblsubtitle.font = [UIFont fontWithName:#"HelveticaNeue" size:10];
// Removed CJamesRun lblsubtitle.textAlignment=UITextAlignmentLeft;
lblsubtitle.shadowColor = [UIColor darkGrayColor];
lblsubtitle.shadowOffset = CGSizeMake(0,0.5);
lblsubtitle.textAlignment = UITextAlignmentCenter;
imgViewlower.tag=3;
lblNamelocal.tag=2;
lblsubtitle.tag=4;
[cell.contentView addSubview:imgView];
[cell.contentView addSubview:imgSaintPic];
[cell.contentView addSubview:imgViewlower];
[cell.contentView addSubview:lblNamelocal];
[cell.contentView addSubview:lblsubtitle];
// cell.layer.masksToBounds = NO;
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
return cell;
}
What I've tired is to rasterize the cell layer, and also to remove the views from the SuperView upon creating a new cell.
Any other suggestions?
I would recommend setting up your cells' subviews just once, and then only updating the contents inside collectionView:cellForItemAtIndexPath:. E.g. you're loading some images in each cell, but those are the same for every cell, so loading them every time the cell is reused is unnecessary.

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.

Resources